简体   繁体   中英

AngularJS : Two way data binding - directive with ng-repeat - not working

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM