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

时间:2013-08-19 15:32:56

标签: angularjs angularjs-scope

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

Link to JSFiddle

为什么我需要调用范围。$ apply即使代码被绑定为按钮点击事件的事件。根据这里的文档http://docs.angularjs.org/guide/scope,这应该是“Angular领域”的一部分。

在澄清上述内容时,有人可以帮助我理解角度领域吗?任何有关改进上述代码的反馈意见也会受到赞赏。

1 个答案:

答案 0 :(得分:4)

正如@DavinTyron所说,按钮点击事件是一个外部事件,不属于“Angular领域”。因此,您需要调用$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的modified version