2014-04-04 23 views
1

我有穿過像這樣的屬性的參照範圍的數據(假設$scope.parent.child存在)一指令的所有元素: <span status-label item='parent.child'></span>AngularJS:使用指令顯示相同的值

該指令的工作原理使用一次時如預期。但是,如果使用多次,並使用不同的item屬性值,則使用該僞指令的所有元素都顯示相同的值。

我的完整代碼如下,一個Plunker在這裏:http://plnkr.co/edit/9ahmua?p=preview。如果您注意到,使用指令(第8行)更改第二個元素的item=值將會將所有元素的值更改爲該值。

我在做什麼不正確?我如何使每個元素/指令的屬性爲單個item屬性?謝謝。

<!DOCTYPE html> 
<html ng-app='familyApp'> 
    <head> 
    <link rel="stylesheet" href="style.css" /> 
    </head> 
    <body> 
    <div ng-controller='BaseController'> 
     <p>{{ parent.child.name }}: <span status-label item='parent.child'></span></p> 
     <p>{{ root.name }}: <span status-label item='root'></span></p> 
    </div> 
    </body> 
    <script data-require="[email protected]" data-semver="1.7.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
    <script src="http://code.angularjs.org/1.2.12/angular.js" data-semver="1.2.12" data-require="[email protected]"></script> 
    <script> 
    var familyApp = angular.module('familyApp', []); 
     angular.module('familyApp').controller('BaseController', 
     function ($scope) { 
      $scope.root = { 
      name: 'Jack', 
      age: 40, 
      flagged: false 
      }; 
      $scope.parent = { 
      child: { 
       name: 'Jill', 
       age: 30, 
       flagged: true 
      } 
      };   
     }); 
     angular.module('familyApp').directive('statusLabel', 
     function ($compile, $parse) { 
      return { 
       link: function (scope, element) { 
        scope.status = function (item) { 
         item = $parse(element.attr('item'))(scope); 
         if (item.flagged === true) { 
          return 'flagged'; 
         } 
         return 'clean'; 
        }; 
       }, 
       transclude: true, 
       template: '<div ng-switch on="status()"><div ng-switch-when="flagged">Flagged</div><div ng-switch-when="clean">Clean</div></div>' 
      }; 
     }); 
    </script> 
</html> 

回答

2

您將希望通過將範圍設置爲某個東西來指示它是自己的範圍。

您可以瞭解更多關於here