我坚持从指令到控制器的双向数据绑定。指令是ng-repeat。尝试了几件事,但无法获得指令范围变量反映在控制器中。
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/
我错过了什么。我也试过使用链接功能,但无济于事。
答案 0 :(得分:6)
将它们放在这样的物体中:
$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的一个很好的答案可以找到here。