Directive working in one controller and not in ano

2019-08-28 02:46发布

问题:

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>

In the HTML view-source I can see rating="3".

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.

Any thoughts/ideas?

回答1:

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>  

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.

Check out this fork of your Plunker.

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});
        }  
    });
}

I updated the Plunker script with the changes above plus a button to simulate a scope change from outside the directive.