Search code examples
javascriptangularjsangularjs-directiveangularjs-scope

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.

Thank you.


Solution

  • parentVar is an array reference, so the items that to add to it can be accessed from both parent controller.

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