具有单向绑定的 Angular 1.5 指令更新父范围



我有一个带有隔离范围和单向绑定变量的指令。然而,当我在指令控制器中更改该变量时,它也会更新父范围。

示例代码:

function someDirective() {
    return {
        restrict: 'E',
        replace: true,
        scope: {},
        bindToController: {
            parentVar: '<'
        },
        templateUrl: templateUrl,
        controller: directiveController,
        controllerAs: 'vm'
    }
}
function directiveController($scope) {
    var vm = this;
    $scope.$watchCollection('vm.parentVar', doSomething);
    function doSomething(newCollection) {
        var some_object = {
            property1: 1,
            property2: 2
        };
        newCollection.unshift(some_object);
    }
}

更新指令中传递的变量后,我在应用程序的其他部分看到some_object

谢谢。

parentVar 是一个数组引用,因此可以从两个父控制器访问要添加到其中的项目。

如果不希望反映来自指令控制器的更改,则必须在对数组进行操作之前克隆该数组。

function directiveController($scope) {
    var vm = this;
    $scope.$watchCollection('vm.parentVar', doSomething);
    function doSomething(newCollection) {
        var clonedCollection = newCollection.slice();
        var some_object = {
            property1: 1,
            property2: 2
        };
        clonedCollection.unshift(some_object);
    }
}

最新更新