AngularJS:双向数据绑定 - 带有ng重复的指令 - 不起作用

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

本文关键字:不起作用 指令 ng 带有 数据绑定 AngularJS      更新时间:2023-09-26

我被从指令到控制器的双向数据绑定所困扰。指令是带有ng重复的。尝试了几件事,但无法让指令范围变量反映在控制器中。

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>

这是JSFIDDLE:http://jsfiddle.net/keshav89/sezknp1t/1/

我错过了什么。我也尝试使用链接功能,但无济于事。

将它们放在这样的对象中:

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

和:

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

演示:http://jsfiddle.net/fzz9xabp/

关于原型遗传和AngularJS的一个很好的答案可以在这里找到。