【问题标题】:Bind to scope from nested resolve function从嵌套解析函数绑定到范围
【发布时间】:2016-01-07 18:27:44
【问题描述】:

我总是遇到这个问题,我试图从嵌套解析函数 (.then()) 绑定到范围,因为我想用数据库中的更新数据刷新视图。

但是,在嵌套解析中,由于某种原因,我永远无法绑定到范围。这对我来说没有意义,因为它从第一次解决就可以正常工作。

虽然有一个简单而乏味的解决方法,将来自第二个解析的数据存储到服务中,然后使用控制器中的观察者检查服务是否发生变化,然后更新范围,但对于这种情况感觉有点过头了一件简单的事情。

从嵌套的解析函数绑定到作用域肯定是一种更干净、更简单的方法吗?

带有解析的示例 api 调用:

// Simple $http.get requests from my factory which gets resolved here
tagApi.delete({id: item.id}).then(function(res) {

    // Binding scope from here works
    $scope.someProp = res;

    tagApi.edit({id: res.id}).then(function(res) {

        // But not from inside here
        $scope.someProp = res;
    });
});

【问题讨论】:

    标签: javascript angularjs angularjs-scope


    【解决方案1】:

    你可以这样试试:

    tagApi.delete({id: item.id})
    .then(function(res) {
    
        // Binding scope from here works
        $scope.someProp = res;
    
        return tagApi.edit({id: res.id});
    })
    .then(function(result) {
      $scope.someProp = result;
    })
    

    【讨论】:

    • 完全忘记了一个解析可以将数据传递给另一个解析,太棒了!效果很好:)
    【解决方案2】:

    你可以在tagApi.delete的成功函数中使用$broadcast

    $rootScope.$broadcast('tag:deleted', res);
    

    然后:

    $rootScope.$on('tag:deleted', editFunc);
    var editFunc = function (event, res) {
      tagApi.edit({id: res.id});
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 1970-01-01
      相关资源
      最近更新 更多