javascript - 数据更改时 Angular 链接不会触发

标签 javascript angularjs data-binding angularjs-directive angularjs-ng-repeat

我有一个项目数组,其中每个项目都绑定(bind)到一个指令。首次构建数组时,一切都很好,但是当我将数组重置为新值时,指令的链接函数不会触发。这是 HTML,其中框架数组的每个元素都包含多个项目,每个项目都绑定(bind)到我的指令 Cool-chart

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>

您会注意到,您看到警报“获取新数据”,但未调用指令链接函数。

我的想法是错误的吗?这里替换数组内容的正确模式是什么,以便每个数组元素处绑定(bind)的数据触发正确的更改通知?

最佳答案

重新分配初始帧数组时,不要破坏对它的引用...而是尝试清空它并将新数据合并到其中,这样引用就不会丢失

// 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 之外的事件引入的,则需要告诉 Angular 使用 $apply() 运行摘要

我删除了 while 循环,因为我不明白为什么需要它

关于javascript - 数据更改时 Angular 链接不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31494972/

相关文章:

javascript - 手动将 js 文件添加到另一个 js 文件之间的页面(订单计数)

javascript - Jquery .text() 剥离 html 在 IE-8 中不起作用

angularjs - 具有多个父状态的 Angular-ui-router 子状态

javascript - Angular 2使用AfterViewInit从文件执行JS

jquery - 如何使 Twitter Bootstrap 按钮组与 AngularJS 一起工作?

javascript - 使用Cesium绘制三 Angular 形时出现错误

javascript - 使用嵌套函数进行 JS 垃圾收集

javascript - 在 Angular.js 工厂中获取外部变量

c# - 当我的 wpf 绑定(bind)验证失败并且包含面板不再可见时,如何摆脱红色矩形?

data-binding - grails datePicker 数据绑定(bind)