我试图编写一个指令,允许我们从列表中删除值。HTML和Javascript代码如下
HTML
<body ng-app="evalModule">
<div ng-controller="Ctrl1">
<input type="text" ng-model="newFriend"></input>
<button ng-click="addFriend()">Add Friend</button>
<ul>
<li ng-repeat="friend in friends">
<div class='deletable' index-value = {{$index}} delete-function="removeFriend(frndToRemove)"> {{$index}} {{friend}} </div>
</li>
</ul>
</div>
</body>
Javascript
function Ctrl1 ($scope) {
$scope.friends = ["Jack","Jill","Tom"];
$scope.addFriend = function () {
$scope.friends.push($scope.newFriend);
}
$scope.removeFriend = function (indexvalue) {
console.log(indexvalue);
var index = $scope.friends.indexOf(indexvalue);
$scope.friends.splice(indexvalue, 1);
}
}
var evalModule = angular.module("evalModule",[]);
evalModule.directive('deletable', function(){
return{
restrict : 'C',
replace : true,
transclude : true,
scope:{
indexValue : '@indexValue',
deleteFunction : '&'
},
template : '<div>'+
'<div> X </div>'+
'<div ng-transclude></div>'+
'</div>',
link:function(scope, element, attrs){
var del = angular.element(element.children()[0]);
del.bind('click',deleteValue);
function deleteValue () {
var expressionHandler = scope.deleteFunction;
expressionHandler({frndToRemove : scope.indexValue});
console.log("deleteValue called with index" + attrs.indexValue);
scope.$apply();
}
}
}
});
为什么我需要调用 scope.$apply 即使代码作为事件绑定到按钮单击事件。根据此处的文档http://docs.angularjs.org/guide/scope这应该是“Angular 领域”的一部分。
有人可以在澄清上述内容的同时帮助我理解角度领域吗?任何有关改进上述代码的反馈也将不胜感激。