AngularJS 在模板中创建新范围? [英] AngularJS Create new scope in template?

查看:20
本文介绍了AngularJS 在模板中创建新范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Symfony2.x,我有一个 twig 循环遍历一些数据的数据,我还有一个 ng-repeat 正在处理类似的元素(不同的是这些元素在后台加载虽然),但两者都共享相同的功能.

我在树枝循环版本中有一些奇怪的功能,这些功能在 ng-repeat 版本中运行良好.我有一种感觉,这只是一个范围问题.

我在文档中读到 ng-repeat 会自动为重复的元素创建一个新的范围,但当然这不会发生在树枝循环中.

如何手动(最好只在模板中)为每个重复元素调用一个新范围?

解决方案

最简单的方法可能是为每个元素添加一个指令.这可以在模板中完成.然后,指令可以请求新范围(通过 scope:truescope:{}),每个重复的元素将获得与其关联的新范围.

您可以在元素上创建指令,例如:

然后在您的代码中,定义指令:

myApp.directive('mydirective',function(){返回 {范围:真实,链接:功能(范围,元素,属性){//在这里做一些范围/元素的事情}}});

Using Symfony2.x, I have a twig loop going through data for some data, and I also have an ng-repeat going on for similar elements (difference being these ones get loaded in the background though), but both are to share the same functionality.

I have some odd functionality going on in the twig loop versions that are working perfectly fine in the ng-repeat versions. I have a feeling it's simply a scope issue.

I read in the docs that ng-repeat will automatically create a new scope for the repeated elements, but of course this doesn't happen with a twig loop.

How does one manually, and preferably exclusively IN the template, invoke a new scope per repeated element?

解决方案

The easiest way might be to add a directive to each element. This can be done in the template. The directive can then request new scope (via scope:true or scope:{}) and each repeated element will get a new scope associated with it.

You can create a directive on an element like:

<div mydirective></div>

Then in your code, define the directive:

myApp.directive('mydirective',function(){
    return {
        scope: true,
        link: function(scope, elem, attrs){
            // do some scope / element stuff here
        }
    }
});

这篇关于AngularJS 在模板中创建新范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆