替换数组中的对象 - Angular绑定是否安全

时间:2013-11-18 13:53:37

标签: angularjs

我正在使用Angular JS,并且我已经使用重置功能实现了我的表单。

  • 当我开始编辑表单上的项目时,将调用setPrimarySelectionEditEntry。 primarySelectionEntry保留绑定到控件的对象
  • 当用户点击保存时,会调用savePrimarySelectionEdit。我所做的是替换primarySelection数组中的item,因为我使用此数组来显示列表
  • cancelPrimarySelectionEdit除了将表单设置为pristine状态外什么都不做。底层阵列保持不变

    $scope.cancelPrimarySelectionEdit = function () {
        $scope.primarySelectionForm.$setPristine();
    };
    
    $scope.savePrimarySelectionEdit = function () {
        $scope.topicSelection.primarySelection[$scope.formEntryIndex] = $scope.primarySelectionEntry;
        $scope.cancelPrimarySelectionEdit();
    };
    
    $scope.setPrimarySelectionEditEntry = function (entry) {
        $scope.formEntryIndex = $scope.topicSelection.primarySelection.indexOf(entry); ;
        $scope.primarySelectionEntry = angular.copy(entry);
    };
    

它的工作原理:当我点击列表中的保存项时会反映新值。当我点击取消时,没有任何反应。但是我想知道这个替换数组项在角度上下文中是否安全?

1 个答案:

答案 0 :(得分:0)

只要您在Angular's execution context内更改模型,就可以安全地替换某些元素甚至整个数组。它不会破坏数据绑定和事件循环。

您只需担心在Angular循环之外进行的更改。例如,指令中的DOM事件侦听器。假设你有以下指令:

angular.module('myApp').directive('resetForm', function(){
    return {
        link: function($scope, $iElement){
            //Add a listener to the element
            $iElement.on('click', function(){
                //Carefull: changes in scope in this context won't trigger an angular event loop.
                $scope.cancelPrimarySelectionEdit();
                //So, call $digest to process all the watchers
                $scope.$digest(); 
                return;
            });
            return;
        }
    }
});

这里,可以随时调用$scope.cancelPrimarySelectionEdit()函数,因此应该添加对$ scope。$ apply()或$ scope。$ digest()的调用,以告诉Angular模型中的某些内容已经改变,需要执行当前范围及其子女的所有观察者。