的问题是,因为由超级英雄指令使用的共享范围。
superhero指令使用父元素作用域作为它自己的作用域,因为您没有为指令使用子/隔离作用域。对于你的样本中的两个超级英雄元素都有相同的范围。
所以第一个超级英雄创建一个空数组属性abilities
并且因为它有一个speed
指令增加了speed
它,那么当第二个超级英雄元素被编译并处理它再次重写这个属性与空数组,因为他们都在工作同一范围
var app = angular.module('myApp', []);
app.directive('superhero', function() {
return {
restrict: 'E',
scope: true,
controller: function ($scope) {
$scope.abilities = [];
this.addStrength = function() {
console.log('adding strength', $scope.$id);
$scope.abilities.push('strength');
console.log($scope.abilities);
}
this.addSpeed = function() {
console.log('adding speed', $scope.$id);
$scope.abilities.push('speed');
console.log($scope.abilities);
}
},
link: function (scope, element) {
console.log('link', scope.$id, scope.abilities)
element.bind('mouseenter', function() {
console.log('me', scope.$id, scope.abilities)
})
}
}
})
演示:Fiddle
谢谢你,完美的作品 –
只是为了检查 - 这是否意味着每个指令有一个单独的范围是什么? –
@DanTang一旦你定义了'scope:true',指令中的元素将有一个单独的范围 –