问题是由于 superhero 指令使用的共享范围。
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)
})
}
}
})
演示:小提琴