【问题标题】:Initialize controller by ajax request通过ajax请求初始化控制器
【发布时间】:2013-09-16 03:42:49
【问题描述】:

我有 AngularJs 控制器:

function MyController($scope, $http) {
   // as $http.get() is async, success() returns promise but 
   // I need the actual value 'items'
   var promise = $http.get(...)
       .success(function(response) {return response.items;});
   <waitForAjaxCall>
   $scope.items = promise.get?();
   $scope.firstItem = $scope.items[0];

   //do stuff using $scope.firstItem
}

var myApp = angular.module('myApp',[]);
myApp.controller('MyController', ['$scope', '$http', MyController]);

如何确保$scope.items$scope.firstItem = ... 赋值之前由ajax 调用返回的值初始化?我看到的另一种方法是将 items 包装在调用 $http 的 angularjs 工厂中,但我仍然需要等待 ajax 调用在该工厂内完成。

【问题讨论】:

  • 为什么不在 promise 的成功回调中设置 $scope.items 的值?
  • @Sneaksta adaiu,在这种情况下 $scope.firstItem 可能指的是未初始化的值
  • 对了。没有在下一行看到对 $scope.items 的引用,抱歉。那么你不能在成功回调中定义 $scope.firstItem 吗?

标签: javascript ajax angularjs


【解决方案1】:

您不能同步等待 Ajax 调用完成。您需要在success 回调中初始化范围:

function MyController($scope, $http) {
    function init(items) {
        $scope.items = items;
        $scope.firstItem = $scope.items[0];

        //do stuff using $scope.firstItem
    }

    $http.get(...)
        .success(function(data) {
            init(data.items);               
        });
}

【讨论】:

    【解决方案2】:

    我实际上会这样做:

    <div>{{items[0].name}}</div>
    

    只要设置了$scope.items,第一项就会绑定在那里。

    【讨论】:

    • 我想我会选择这种方法,因为它使控制器不必担心如何/何时获取数据。这就是拥有服务的想法,所以我说把它留给他们,让控制器担心它的问题(数据绑定)。
    • 它非常接近我的需要,只是再澄清一点:$scope.firstItem 是一个承诺对象,在你的演示中,这个值用作 {{firstItem}},所以我理解角度更新{{ }} 中的 value 自动使用 promise 封装的 value 而不是 promise 本身,对吧?另外,如果它是一个承诺对象,我如何读取控制器中的 firstItem 值,我不能只做var myItemName = $scope.firstItem.getItemName()...
    • @Nutel Woaaah 这令人困惑。真的,这一切有点傻。为什么不只是绑定东西? &lt;div&gt;{{items[0].name}}&lt;/div&gt; 完全忽略$scope.firstItem??
    • 我打算在控制器中使用这个值,例如if ($scope.firstItem.name == 'admin') {console.log('admin');}
    • 我认为没有必要这样做。如果我不得不猜测,您需要在视图中进行条件绑定,在这种情况下,您应该在视图中有条件地绑定它:)
    猜你喜欢
    • 2015-02-28
    • 1970-01-01
    • 2016-02-29
    • 2017-03-21
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    相关资源
    最近更新 更多