范围不是使用JSON调用更新的,而是使用custom指令中的简单整数赋值进行更新

时间:2015-03-24 08:36:10

标签: angularjs angularjs-directive angularjs-scope

我有两个不同的值分配给我的$ scope。一个是$ scope.summary,它是一个JSON对象,另一个是$ scope.myNumber,它被赋值为3.

来自控制器:

myService.loadSummary(function(data) {
    $scope.summary = data;
    $scope.$apply();
});

$scope.myNumber = 3;

myService包含一个名为loadSummary的函数,它可以很好地工作,我可以在debug $ scope.summary中看到它获取它应该得到的数据。我还看到在调试中将$ scope.myNumber分配给3。

当我在调试中转到我的指令时,它只显示myNumber值。 $ scope.summary没有任何内容。这是未定义的。

来自指令:

define([ 'angular', 'directives-module', 'text!./tmpl/table.html' ], function(
    angular, directives, tmpl) {
    directives.directive('summaryTable', function($timeout) {
        return {
            restrict: "E",
            template: tmpl,
            link: function(scope, elm, attrs) {
                require([ 'jquery', 'datagrids' ], function($) {
                    var data = scope.summary;

可能是什么原因?

我对Angular的知识非常有限。

1 个答案:

答案 0 :(得分:0)

我认为这是因为您的更新应该在$apply()表达式中,如下所示:

myService.loadSummary(function(data) {        
    $scope.$apply(function(){
        $scope.summary = data;
    });
});

看到这个好article。引用:

  

如果要在新回合中运行代码,则需要使用它( $ apply())。并且只有当没有从AngularJS库中的方法创建该转弯时。在新的回合中,您应该将代码包装在$ scope中。$ apply()