【问题标题】:not updating view after Ajax call in AngularJS?在 AngularJS 中调用 Ajax 后不更新视图?
【发布时间】:2020-04-04 12:21:08
【问题描述】:

我正在调用 get 方法,但视图没有更新。我试过alert(),它可以正确显示数据。

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

app.controller('TestCtrl', function ($scope) 
{
    $.get( "people/allNumberOfuser", function( data )
    {
        $scope.testValue =data.message;
        alert(data.message);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="test">
    <p ng-controller="TestCtrl">
        {{testValue}}
    </p>
</div>

我是 AngularJS 的新手。提前致谢。

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

JQuery get 回调方法无法通过 Angular 检测,因为它在 Angular 之外,因此需要使用 $scope.$apply() 通知 Angular 任何更新

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

app.controller('TestCtrl', function ($scope) 
{
   jQuery.get( "/People/GetNumberOfUser", function( data )
   {
       $scope.testValue =data.message;
       $scope.$apply() ;
       alert(data.message);
   });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="test">
<p ng-controller="TestCtrl">
{{testValue}}
</p>
</div>

你可以使用 angular $http 代替 jquery 然后不需要$scope.$apply()

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

app.controller('TestCtrl', function ($scope) 
{
    $http({
      method: 'POST',
      url: '/People/GetNumberOfUser'
    }, function( data )
    {
       $scope.testValue =data.message;
       alert(data.message);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="test">
<p ng-controller="TestCtrl">
{{testValue}}
</p>
</div>

【讨论】:

  • @31piy 谢谢,我已经使用$http 服务更新了我的编码
猜你喜欢
  • 2016-12-15
  • 1970-01-01
  • 1970-01-01
  • 2015-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多