【问题标题】:Angular 1.5 directive with one-way binding updates parent scope具有单向绑定的 Angular 1.5 指令更新父范围
【发布时间】:2017-06-08 07:54:14
【问题描述】:

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

示例代码:

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

谢谢。

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope


    【解决方案1】:

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

    【讨论】:

    • 谢谢,这正是我所做的。这是预期的行为吗?
    • 是的。 '
    猜你喜欢
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 2015-05-14
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    相关资源
    最近更新 更多