AngularJS范围变量未在指令中的匿名回调函数中更新

问题描述 投票:0回答:1

我一直在尝试使用REST API中的轮询数据(每秒)创建一个cubism.js图。

似乎将正确的值传递给了指令,但是没有将其传递给匿名回调函数。

如果我正确理解,则伪指令中的匿名回调函数应该可以访问参数变量val

将在视图中更新正确的值,并在指令的其余部分中更新。但是,现在看来,参数值val(在promise解析为回调函数notifyCall(data)时已从控制器更新)尚未在指令的匿名回调函数中进行更新。

我尝试过的方法:

  • random功能放入控制器中的notifyCallback功能。->无效
  • $scope.$apply包裹在$scope.sysHeapMemoryPercent上-> $digest error
  • 在指令中使用scope.watch代替attrs.$observe->与attrs.$observe方法具有相同的结果

我该如何解决这个问题?我需要使用闭包吗?

Controller

'use strict';
angular.module('adminControllers')
.controller('pollerController', ['$scope', '$resource', 'poller', function ($scope, $resource, poller) {

  $scope.sysHeapMemoryPercent=0;

  // ......
  // Some codes that makes polling API calls every second
  // using $resource and Angular Poller
  // ......

  myPoller.promise.then({}, {}, notifyCallback); 

  function notifyCallback(data){
    $scope.sysHeapMemoryPercent = Number(data[0].value.used) / Number(data[0].value.max);
    }
}]);

Directive

'use strict';
angular.module('adminControllers')
 .directive('sysHeapMemoryDirective', function ($timeout) {

 return {
 restrict: 'AE',
 link: function (scope, element, attrs) {
    var context = cubism.context().serverDelay(0).clientDelay(0).step(1000).size(594);


  attrs.$observe('memory', function (newVal,oldVal) {
    console.log(oldVal); // prints undefined every second
    console.log(newVal); // prints the correct value every second

    var constantNum = 0.123;
    compute(constNum); // works
    compute(newVal); // Doesn't work. Some child values are returned as null
  });


  function compute(val) {
    var value = 0, values = [],
    i = 0, last; 

    console.log(val); // prints the correct value every second

    return context.metric(function (start, stop, step, callback) {
      start = +start, stop = +stop;

      console.log(val); // prints 0 every second

      if (isNaN(last)) last = start;
      while (last < stop) {
        last += step;
        values.push(val);
      }
      callback(null, values = values.slice((start - stop) / step));
    }, "Demo");
  }
}
};
});

HTML

<div ng-controller="pollerController">
 {{sysHeapMemoryPercent}}  // successfully shows the updated value every second
   <sys-heap-memory-directive memory="{{sysHeapMemoryPercent}}"> </sys-heap-memory-directive>
</div>
angularjs angularjs-directive angularjs-scope dom-events cubism.js
1个回答
1
投票

我不确定是否可以回答自己的问题,但是当我尝试其他方法来解决问题时,我找到了解决方案。

这里的问题是AngularJS的“脏检查”是基于对象的,而我试图将$ scope.sysHeapMemoryPercent保存为原始类型(数字)而不是对象。

此链接对我很有帮助,有助于了解AngularJS如何在后台更新范围变量。Auto-updating scope variables in angularjs

当我将响应包装为对象时,它工作正常!

$scope.sysHeapMemoryPercent={};
// .............
function notifyCallback(data){
  $scope.sysHeapMemoryPercent.value = Number(data[0].value.used) / Number(data[0].value.max);
}
© www.soinside.com 2019 - 2024. All rights reserved.