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.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Keshav Agrawal
  • 577
  • 9
  • 23
  • 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. – squiroid Jan 15 '15 at 06: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? – Keshav Agrawal Jan 15 '15 at 06:16
  • @squiroid I get it now what you were trying to say. Thanks – Keshav Agrawal Jan 15 '15 at 06: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. – squiroid Jan 15 '15 at 06:40

1 Answers1

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.

Community
  • 1
  • 1
tasseKATT
  • 38,470
  • 8
  • 84
  • 65