3

I am stuck with two way data binding from directive to controller. Directive is with ng-repeat. Tried several things but cant get directives scope variable reflect back in controller.

angular.module("myApp", [])
.controller("Ctrl1", function ($scope) {
    $scope.crossTabs = [1,2,3,4,5];   
})
.directive("crossTab", function () {
    return {
        restrict: "E",
        template: "<input type='text' ng-model='crossTab'/><button ng-click='changeLols()' id='clc'>change crossTabs</button>",
        scope: {
            crossTabs: '=',
            crossTab: '='
        },
        controller: function($scope){
            $scope.changeLols = function(){
                // The below comment line is not working. It doesnt change anything. But the one uncommented which pushes an element updates the controllers 'crossTabs' variable as well. 
                 //$scope.crossTabs = [3,4,5];
                 $scope.crossTabs.push(6);                 
            }
        },
        link: function (scope, elem, attrs) {   

        }
    }
});

HTML

<div ng-app="myApp" ng-controller="Ctrl1">
    <div> Controller: {{ crossTabs }}</div><br>
    <h5>Directive Section below</h5>
    <cross-tab ng-repeat="crossTab in crossTabs" cross-tab="crossTab" cross-tabs="crossTabs"></cross-tab>
</div>

here is the jsfiddle: http://jsfiddle.net/keshav89/sezknp1t/1/

What am I missing. I tried using link function as well but to no avail.

4
  • 1
    As we know ng-repeat creates a Prototypal inheritance which inherit the scope of parent(in this case controller) but with a new property which is the value of 'crossTab' in your case.So crossTab doesn't belong to the controller scope but crossTabs do. Commented Jan 15, 2015 at 6:13
  • Mmm. So the issue is I want to change the crossTabs variable in directive and have that reflected in parent controller's scope. how to go about it? Commented Jan 15, 2015 at 6:16
  • @squiroid I get it now what you were trying to say. Thanks Commented Jan 15, 2015 at 6:37
  • hmm but still i m trying to figure out how to reflect the directive scope to ng-repeat scope and then ng-repeat scope to controller scope. Commented Jan 15, 2015 at 6:40

1 Answer 1

6

Put them in an object like this:

$scope.viewModel = {
  crossTabs: [1, 2, 3, 4, 5]
};

And:

<cross-tab ng-repeat="crossTab in viewModel.crossTabs" cross-tab="crossTab" cross-tabs="viewModel.crossTabs">

Demo: http://jsfiddle.net/fzz9xabp/

A great answer regarding prototypal inheritance and AngularJS can be found here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.