Angularjs 同一控制器中的两个作用域(一个来自服务)与指令之间有什么区别?

Angularjs 同一控制器中的两个作用域(一个来自服务)与指令之间有什么区别?,angularjs,angularjs-directive,angularjs-scope,Angularjs,Angularjs Directive,Angularjs Scope,下面的控制器有两个作用域变量,只有一个传递到我的指令 .controller('newsController', ['$scope', 'gasPrices', function($scope, gasPrices) { gasPrices.success(function(data) { $scope.gasFeed = data.series[0]; }); $scope.myData02

下面的控制器有两个作用域变量,只有一个传递到我的指令

.controller('newsController', ['$scope', 'gasPrices',
                                  function($scope, gasPrices) { 

  gasPrices.success(function(data) {
    $scope.gasFeed = data.series[0];    
  });

  $scope.myData02 = [2.095,2.079,2.036,1.988,1.882,1.817,1.767,1.747];

}])
;
我有一个指令,它接受一个作用域,但不接受另一个

这很有效

<line-chart chart-data="myData02"></line-chart>

这并不重要

<line-chart chart-data="gasFeed"></line-chart>


您知道为什么吗?

您必须延迟实例化指令,直到异步服务中的数据可用为止。比如:

<line-chart ng-if="gasFeed" chart-data="gasFeed"></line-chart>


在gasFeed scope属性具有数据之前,不应实例化该指令。

您必须延迟实例化该指令,直到异步服务中的数据可用为止。比如:

<line-chart ng-if="gasFeed" chart-data="gasFeed"></line-chart>

在gasFeed scope属性具有数据之前,不应实例化该指令。

尝试以下操作:

.controller('newsController', ['$scope', 'gasPrices',
                                  function($scope, gasPrices) { 
  //Create a object that will be pass in the directive, then when this variable
  //it's loaded, the value in the directive (if the scope of the directive uses the '=' binding) will be updated
  $scope.gasFeed = {}; 

  gasPrices.success(function(data) {
    $scope.gasFeed = data.series[0];    
  });

  $scope.myData02 = [2.095,2.079,2.036,1.988,1.882,1.817,1.767,1.747];

}]);
试试这个:

.controller('newsController', ['$scope', 'gasPrices',
                                  function($scope, gasPrices) { 
  //Create a object that will be pass in the directive, then when this variable
  //it's loaded, the value in the directive (if the scope of the directive uses the '=' binding) will be updated
  $scope.gasFeed = {}; 

  gasPrices.success(function(data) {
    $scope.gasFeed = data.series[0];    
  });

  $scope.myData02 = [2.095,2.079,2.036,1.988,1.882,1.817,1.767,1.747];

}]);

这里,在您的示例中,只有当服务成功回调时,您才能访问
gasFeed
范围。因此,在此之前将加载
myData02
范围

如果您想同时访问这两个。然后试试这个

.controller('newsController', ['$scope', 'gasPrices',
                                  function($scope, gasPrices) { 

  gasPrices.success(function(data) {
    $scope.gasFeed = data.series[0];
    $scope.myData02 = [2.095,2.079,2.036,1.988,1.882,1.817,1.767,1.747];    
  });
}]);

这里,在您的示例中,只有当服务成功回调时,您才能访问
gasFeed
范围。因此,在此之前将加载
myData02
范围

如果您想同时访问这两个。然后试试这个

.controller('newsController', ['$scope', 'gasPrices',
                                  function($scope, gasPrices) { 

  gasPrices.success(function(data) {
    $scope.gasFeed = data.series[0];
    $scope.myData02 = [2.095,2.079,2.036,1.988,1.882,1.817,1.767,1.747];    
  });
}]);

当成功回调时,gasFeed将可用。同时,当控制器加载时,myData02将加载数据。谢谢Thillai,这很有意义。我将研究如何延迟或解决成功回调延迟。当有成功回调时,gasFeed将可用。同时,当控制器加载时,myData02将加载数据。谢谢Thillai,这很有意义。我将研究如何延迟或解决成功回调延迟。