Reputation: 597
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.
Upvotes: 3
Views: 2421
Reputation: 38490
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.
Upvotes: 6