【问题标题】:Update View when Scope changes Angular jsScope更改Angular js时更新视图
【发布时间】:2014-07-22 11:52:07
【问题描述】:

我正在开发一个有角度的社交应用程序,我几乎没有与范围绑定相关的问题。 我有一个来自 http 服务的范围数据,其中列出了用户的订阅者。每当在寻找 用户搜索任何用户并想添加他然后此时我进行 http 调用并返回订阅者列表的更新数据。但它不会在不刷新页面的情况下更新视图。我可以为此使用间隔,但我认为这不是解决方案,因为它会通过发出常规 http 请求给我的服务器增加更多负载。

JS

 this.loadsubscribers = function (){
 myService.subscriber().then(function(response){
     $scope.subscriber = response.data;         
    });
 }

 // i can make interval call for getting subscriber list but this will put load to my server.  

 $interval(function(){
  this.loadsubscribers();
 }.bind(this), 10000);   

this.loadsubscribers();

当用户单击添加订阅者按钮时,我需要更新此范围: 在这里,当用户单击添加订阅者检查功能时,会调用并通过 http 调用将该用户添加到订阅者列表中。保存数据后,我将当前订阅者列表返回到 http 成功。但它不会更新视图。

$scope.checkit = function(value,id,firstname,str){      

    if(text === 'get along'){
    $http.post(baseurl+"ajax/subscriber_post", "subscriber_id="+value).success(function(data){
       //here i have to update scope subscriber and 
       // refresh view  as you can see i am doing it but it doesn't update view.  
      $scope.subscriber =data; 
      growl.addSuccessMessage( firstname+" is your fellow now");    
      $scope.datatocheck.push(value);
      $scope.Checkfriend(value); 
    });
}

interval 有效,但我不想使用它。那么当数据不需要任何同步更新时,最好的方法是什么。

【问题讨论】:

    标签: angularjs angularjs-scope angular-scenario


    【解决方案1】:

    试试这个:

    $scope.$eval(function() {
        $scope.subscriber = data;
    });
    

    如果您仍然遇到摘要循环问题,请尝试使用 $evalAsync 而不是 $eval

    【讨论】:

    • 你能创建一个 jsfiddle/plunkr 来重现这个问题吗?
    【解决方案2】:

    改变这一行:

    $scope.subscriber =data; 
    

    到这里:

    $scope.$apply(function() {
        $scope.subscriber =data; 
    });
    

    【讨论】:

      猜你喜欢
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多