【问题标题】:AngularJS scope variable undefinedAngularJS范围变量未定义
【发布时间】:2015-05-26 21:12:10
【问题描述】:

我是 AngularJS 的新手,在使用范围变量时遇到了一些麻烦。

这是一个示例代码。我想知道为什么使用 ng-repeat 它会显示 $scope.currencies 的值,但是当我尝试从 JS 访问时(console.log($scope.currencies))它返回“未定义”

<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="appCtrl">

<ul>
  <li ng-repeat="x in currencies">
    {{ x }}
  </li>
</ul>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('appCtrl', function($scope, $http) {
  $http.get("http://localhost:8080/currencies")
  .success(function (response) {$scope.currencies = response;});


  console.log("currencies are "+$scope.currencies);
});
</script>

</body>
</html>

我认为我对范围有误,谁能给我一个线索?

【问题讨论】:

  • 您的 console.log 正在运行,然后来自 $http.get 的响应可以触发 .success 方法。此时,$scope.currencies 仍未定义。
  • 您对 $q/$http/promises 的看法有误。

标签: javascript angularjs angularjs-scope angularjs-http


【解决方案1】:

您的 console.log 语句在 .success 方法之外。因此,它将立即运行。你应该把它放在 .success 方法中,像这样:

var app = angular.module('myApp', []);
app.controller('appCtrl', function($scope, $http) {
  $http.get("http://localhost:8080/currencies")
  .success(function (response) {
      $scope.currencies = response;
      console.log("currencies are "+$scope.currencies);
  });
});

另外,尝试使用 $log.debug() 而不是 console.log()。

app.controller('appCtrl', function($scope, $http, $log) {
...
  .success(function (response) {
      $scope.currencies = response;
      $log.debug("currencies are "+$scope.currencies);

【讨论】:

  • 感谢您的回答。实际上我认为我还不够明确,我已经尝试过您的建议,并且效果很好,但是我真正想做的是在 .success 方法之外访问控制器中的 $scope.currencies (我使用了控制台.log 只是作为测试)。我想我不太了解 Promise 是如何工作的,但是现在,如果我只了解如何从控制器主体中访问 $scope.currencies 而不必使用角度指令来访问,我会很高兴的。
  • 好的,让我再次尝试帮助您:您可以随时使用范围属性。它们应该与视图上的元素绑定(使用 ng-data)。 Angular 将负责刷新绑定到属性的任何元素,以反映该属性的任何更改。要理解它,您可以在页面的任何位置放置一个&lt;span&gt;{{currencies}}&lt;/span&gt;,并且您会看到它在每次更改 $scope.currencies 值时自动更改(就像在 .success 方法上发生的那样)。
  • 因此,您的 console.log 将无法执行您期望的操作(“监视”该属性),因为它会立即运行,而且只会运行一次。它将在运行时获取值,但不会在属性发生任何更改后获取。
  • 还有一件事:您的货币属性是用数组还是值填充?
  • 我了解 Angular 中的双向绑定原则,但我想做的有点不同。最初我有一个在某个事件上调用的函数,并尝试自定义绑定的应对变量。但是,当我使用在 $http.get 调用中初始化的变量时,它只能从 Angular 指令中访问,如果从我的 javascript 控制器中的其他任何地方调用,则它是未定义的。我想我没有通过试图简化案件来说明清楚,对此感到抱歉! ^^
猜你喜欢
  • 2013-06-05
  • 1970-01-01
  • 2014-05-28
  • 1970-01-01
  • 2013-06-27
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
相关资源
最近更新 更多