什么时候使用$ scope是安全的。$ apply()? [英] When is it safe to use $scope.$apply()?

查看:350
本文介绍了什么时候使用$ scope是安全的。$ apply()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这个标题非常清楚我要问的是什么。我创造了这个小提琴: http://jsfiddle.net/Sourabh_/HB7LU/13142/

I guess the title is pretty much clear what I am asking. I have created this fiddle : http://jsfiddle.net/Sourabh_/HB7LU/13142/

在小提琴中,我试图复制一个 async 场景。这只是一个示例,但在AJAX调用中,如果我不使用 $ scope。$ apply()列表不会更新。我想知道使用 $ scope是否安全。$ apply()每次我进行AJAX调用来更新列表或者是否有其他机制我可以做使用?

In the fiddle I have tried to replicate an async scenario. This is just an example but in an AJAX call if I don't use $scope.$apply() the list does not get updated. I want to know if it is safe to use $scope.$apply() every time I make an AJAX call to update a list or is there some other mechanism I can make use of?

我编写的代码用于复制场景(与小提琴相同):

HTML

<div ng-controller="MyCtrl">
  <li ng-repeat="item in items">
    {{item.name}}
  </li>
  <button ng-click="change()">Change</button>
</div>

JS

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
  $scope.items = [{name : "abc"},{name : "xyz"},{name : "cde"}];

  $scope.change = function(){
    test(function(testItem){
      $scope.items = testItem;
      //$scope.$apply();
    })
  }
  function test(callback){
    var testItem = [
                    {name : "mno"},
                    {name : "pqr"},
                    {name :   "ste"}
                   ];
    setTimeout(function(){callback(testItem)},2000);
  }
}


推荐答案

如果你想要移植API-Rest-Call,在 Controller 中使用返回的 promise ,而不是在休息呼叫。

If you want to immidate an API-Rest-Call, use the returned promise in your Controller instead setting the scope inside the Rest-Call.

$http.get('uri')
  .success(function(data) {
    $scope.items = data
});

避免使用 $ apply()来自Angular GitHub Repo


$ scope。$ apply()应尽可能接近async事件绑定为
可能。

$scope.$apply() should occur as close to the async event binding as possible.

请勿在整个代码中随意添加。如果您正在执行
(!$ scope。$$阶段)$ scope。$ apply()这是因为你在调用堆栈中不够高

Do NOT randomly sprinkle it throughout your code. If you are doing if (!$scope.$$phase) $scope.$apply() it's because you are not high enough in the call stack.

致你的问题:


  • 如果你发现自己在在你需要$ apply()的情况下,重新考虑你的结构。

  • 出于安全原因:永远不要使用 $ apply()

  • If you find yourself in a situation where you need $apply(), rethink your structure.
  • Just for safety reason: Never use $apply()

这篇关于什么时候使用$ scope是安全的。$ apply()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆