Suj*_*ier 2 asp.net ajax angularjs
我想使用ng-repeat指令将一些数据绑定到div.虽然调用成功,但我获取数据并将其存储在范围变量中,以便能够使用ng-repeat显示它
<div data-ng-app="myapp" id="sidestatus" style="position:fixed;top:50%;right:0;height:200px;width:200px;background-color:red;" data-ng-controller="myctrl">//wont bind here after successful execution
<ul>
<li data-ng-repeat="x in obj">
{{x.heading+' '+x.id+' '+x.name }}
</li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
我的javascript
var app = angular.module("myapp", []);
app.controller("myctrl", function ($scope, $http) {
var obj2=new Array();
$.ajax({
type: "POST",
url: "NotifierService.asmx/getdata",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function (response) {
var res = response.d;
var res4 = res.split(",");
for (var i = 0; i < res4.length; i++) {
var res2 = res4[i].split(":");
obj2[i] = {}
obj2[i].heading = res2[0];
var res3 = res2[1].split("/");
obj2[i].id = res3[0];
obj2[i].name = res3[1];
}
$scope.obj = obj2;
//successfully execute the success function everytime
},
error:function () { alert("failure");}
});
});
Run Code Online (Sandbox Code Playgroud)
正在发送的数据
"heading1:23/name1,heading2:24/name2"
Run Code Online (Sandbox Code Playgroud)
小智 8
无论何时在AngularJS"受控"函数之外执行某些代码,AngularJS都不知道任何作用域中是否有某些内容发生了变化,因此它不会尝试查找更改并根据更改修改演示文稿是的.
在您的代码中,您正在使用jQuery进行Ajax调用.该Ajax调用的回调是在AngularJS控制代码之外执行的,它发生在我之前解释过的内容中.因此,您需要做的是告知AngularJS范围内可能已发生变化.您有两种选择.
$ scope.$ digest()用于告诉AngularJS检查更改.所以你的代码看起来像这样:
success:function (response) {
var res4 = res.split(",");
var res = response.d;
for (var i = 0; i < res4.length; i++) {
//...
}
$scope.obj = obj2;
$scope.$digest(); //hey AngularJS, look for changes to update the scope!
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用$ scope.$ apply.此方法告诉AngularJS执行作为参数传递的函数,然后(函数是否正确执行,抛出和错误)检查范围的变化.所以你的代码可能看起来像:
success:function (response) {
$scope.$apply(function() { //hey AngularJS, execute this function and update the view!
var res = response.d;
var res4 = res.split(",");
for (var i = 0; i < res4.length; i++) {
//...
}
$scope.obj = obj2;
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4964 次 |
| 最近记录: |