具有单向绑定的Angular 1.5指令更新父作用域

时间:2017-01-23 17:51:16

标签: javascript angularjs angularjs-directive angularjs-scope

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

示例代码:

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

谢谢。

1 个答案:

答案 0 :(得分:0)

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);
    }
}