简体   繁体   English

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

[英]Angular 1.5 directive with one-way binding updates parent scope

I have a directive with an isolated-scope and one-way binding variable. 我有一个带有隔离范围和单向绑定变量的指令。 yet when i change that variable in the directive controller it updates the parent scope as well. 但是,当我在指令控制器中更改该变量时,它也会更新父作用域。

Example code: 示例代码:

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

After I update the passed variable in the directive, I see some_object in other parts of my app. 更新指令中传递的变量后,我在应用程序的其他部分看到了some_object

Thank you. 谢谢。

parentVar is an array reference, so the items that to add to it can be accessed from both parent controller. parentVar是一个数组引用,因此可以从两个父控制器访问要添加到其中的项目。

If you do not want the changes from directive controller to be reflected, you will have to clone the array before you operate on it. 如果您不希望反映对指令控制器的更改,则必须先克隆该数组,然后再对其进行操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM