我有一个项目数组,其中每个项目都绑定到一个指令。首次构建数组时,一切都很好,但是当我将数组重置为新值时,指令的链接函数不会触发。这是HTML,其中框架数组的每个元素都包含许多项目,每个项目都绑定到我的指令,酷图表
var app = angular.module("theapp", []);
app.controller("controller", function($scope) {
$scope.frames = []
$scope.getData = function() {
var frames = ["adsf","qwerty"];
alert("got new Data")
$scope.frames.push(frames)
}
});
app.directive('coolChart', function() {
return {
restrict: 'E',
scope: {
data: '=data'
},
link: function(scope, element) {
data = data.toUpperCase();
alert("Link called with: " + data)
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="theapp">
<div ng-controller="controller">
{{frames}}asdf
<button ng-click="getData()">run get Data</button>
<div class="outer-frame" ng-repeat="frame in frames track by $index">
{{frame}}
<div class="chart-container" ng-repeat="item in frame track by $index">
{{item}}
<cool-chart data="item"></cool-chart>
</div>
</div>
</div>
</body>
您会注意到您看到警报“获取新数据”,但未调用指令链接功能。
我在想这个错吗?这里更换数组内容的正确模式是什么,以便每个数组元素绑定的数据触发正确的更改通知?
答案 0 :(得分:0)
尝试在重新分配时不要破坏对初始帧数组的引用...而是尝试将其清空并将新数据合并到其中,以便引用不会丢失
// declare empty array on scope
$scope.frames = [];
var getData = function () {
// reset scope array
$scope.frames.length = 0;
// merge data into frames
$scope.frames.concat(data); // not sure where data comes from
};
或者,如果从角度以外的事件引入数据,则需要告诉angular使用$ apply()运行摘要
我拿出while
循环因为我不明白为什么需要它
答案 1 :(得分:0)
我已经整理了一个类似于你的代码的代码片段。当你运行代码段时它似乎有效。如果可以,请以类似的方式编辑您的问题,以尝试解决问题:)
更新:现在该链接会按预期触发警报。
var app = angular.module("theapp", []);
app.controller("controller", function($scope) {
$scope.frames = []
$scope.getData = function() {
var frames = ["adsf", "qwerty"];
console.log("got new Data")
$scope.frames.push(frames)
}
});
app.directive('coolChart', function() {
return {
restrict: 'E',
scope: {
data: '=data'
},
link: function(scope, element) {
scope.data = scope.data.toUpperCase();
alert("Link called with: " + scope.data)
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="theapp">
<div ng-controller="controller">
{{frames}}asdf
<button ng-click="getData()">run get Data</button>
<div class="outer-frame" ng-repeat="frame in frames track by $index">
{{frame}}
<div class="chart-container" ng-repeat="item in frame track by $index">
{{item}}
<cool-chart data="item"></cool-chart>
</div>
</div>
</div>
</body>