I want to use the ng-repeat directive to bind some data to a div. though the call is successful and i am getting the data and storing it in a scope variable im anot able to use the ng-repeat to display it
<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>
my 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");}
});
});
data being sent
"heading1:23/name1,heading2:24/name2"
Whenever you execute some code outside AngularJS "controlled" functions, AngularJS doesn't know if something may have change in any of the scopes, and because of this it don't try to find the changes and modify the presentation with the changes if there are any.
In your code, you are making an Ajax call with jQuery. The callback of that Ajax call is executed outside of AngularJS controlled code and it happens what I explained previously. So what you have to do is inform AngularJS that something may have changed in the scope. You have two options to do this.
$scope.$digest() is used to tell AngularJS to check for changes. So you're code could look something like this:
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!
}
Another way is to use $scope.$apply. This method tells AngularJS to execute the function passed as an argument and afterwards (whether the function executed correctly or not, throwing and error for example) check for changes in the scopes. So your code could look something like:
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;
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With