指令中的一个控制器,而不是工作在另一 [英] Directive working in one controller and not in another
问题描述
我试图遵循AngularJS的 foodMe 的例子。我在步骤21,而不是创建一个NG-模式,我试图做到这一点有点不同,创造了一个的 Plunker这里。我的问题是,它只能在Restaurants.html,而不是内部Menu.html。我甚至可以看到的价值{{restaurant.rating}}当我查看源,例如
I am trying to follow the foodMe example on AngularJS. I am on step 21. Instead of creating a ng-model, I tried to do it a bit different, created a Plunker here. My issue is it only works in Restaurants.html and not inside Menu.html. I can even see the value of {{restaurant.rating}} when I view the source , e.g.
<span stars rating="{{restaurant.rating}}" readonly="true"></span>
在HTML查看源代码,我可以看到等级=3。
In the HTML view-source I can see rating="3".
从我plunker只有一个小的变化VS沙我在我的沙盒我使用'餐厅'资源来获取个人数据餐厅。
Only a small change from my plunker vs my sandbox is in my sandbox I use the 'Restaurant' resource to get the individual restaurant data.
任何想法/想法?
推荐答案
现在的问题是,物业餐饮
是 Menu.html
你没有访问它的正确方法。将其更改为
The problem is that the property restaurants
is an array of objects and in the Menu.html
you aren't accessing it the proper way. Change it to
Menu Rating: {{restaurants[0].rating}}
<br />
<span stars rating="{{restaurants[0].rating}}" readonly="true"></span>
和它会工作。同样在 Restaurants.html
,因为你通过数组用 NG-重复迭代
。
and it'll work. The same doesn't happen in the Restaurants.html
because you're iterating through the array by using a ng-repeat
.
查看您Plunker这个叉。
更新在评论@parsh交谈后,我能更好地理解他的code中的问题。问题是,该指令没有得到重新渲染时,其变化范围。可以通过使用手表固定
Update After talking with @parsh in the comments, I could better understand the problem with his code. The issue is that the directive doesn't get re-rendered when its scope changes. That can be fixed by using a watch:
link: function (scope, element, attrs, ctrl) {
scope.$watch('rating', function() {
scope.stars = [];
for (var i = 0; i < 5; i++) {
scope.stars.push({'fm-selected': i < scope.rating});
}
});
}
我更新了 Plunker脚本与上面的变化加一个按钮来的从外面指令模拟范围变更。
I updated the Plunker script with the changes above plus a button to simulate a scope change from outside the directive.
这篇关于指令中的一个控制器,而不是工作在另一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!