为什么scope.apply是必需的,即使函数是作为事件处理程序的一部分调用的



我试图编写一个指令,允许我们从列表中删除值。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();
            }
        }
    }
});

链接到JSFiddle

为什么我需要调用scope$应用,即使代码作为事件绑定到按钮单击事件。根据这里的文件http://docs.angularjs.org/guide/scope这应该是"角度领域"的一部分。

有人能在澄清以上内容的同时帮助我理解角度领域吗?任何关于改进上述代码的反馈也将不胜感激。

正如@DavinTyron所说,按钮点击事件是一个外部事件,而不是"角度领域"的一部分。因此,您需要调用$scope.$apply()来触发摘要循环并更新DOM。

不过,在您的情况下,您不需要手动绑定click事件。您可以使用ng-click

template: '<div>'+
          '<div ng-click="delete()"> X </div>'+
          '<div ng-transclude></div>'+
          '</div>',
link: function(scope) {
    scope.delete = function () {
        scope.deleteFunction({frndToRemove : scope.indexValue});
        console.log("deleteValue called with index" + attrs.indexValue);                
    };
}

由于正在使用ng-click,因此无需调用$scope.$apply()。这是jsFiddle的修改版本。

最新更新