Reputation: 4361
I am working with Angular and i am trying to update data of a ng-view when we click on the button but it's not working. Here my code snippet. main page
<body ng-app="app">
<div ng-controller="MyController" >
<a href="#" ng-click="loadDatas()">Load datas</a>
<div ng-view></div>
</div>
</body>
The ng-view:
<div>
{{myValue}}
</div>
<div>
<li ng-repeat ="data in datas">
{{data.name}} || {{data.value}}
</li>
</div>
The loadDatas function :
$scope.loadDatas = function(){
$http.get('data.json')
.then(function(res){
$scope.datas = res.data;
});
};
I want to load datas when the link is clicked.But it's not working. I have a plunker here if someone could help me. Thanks
Upvotes: 1
Views: 910
Reputation: 37701
Since it's an async call, the easiest way would be to wrap the var change in a $timeout callback:
$scope.loadDatas = function(){
$http.get('data.json')
.then(function(res){
$timeout(function(){
$scope.datas = res.data;
}, 0);
});
};
This basically forces a scope digest without you having to worry about the digest phase. Of course, don't forget to inject $timeout into the controller.
If you still want to do the digest manually, you can do $scope.$apply()
.
You also need to fix your JSON as I have shown how you in the comments:
{"name":"Dan","value":"13"},
{"name":"John","value":"34"},
etc...
No need to assign the same controller twice.
Specifying the controller in the route cause the controller to spawn a new scope (and plus one each time that anchor is clicked, unless you remove the href attribute or block it in another way). I fixed it by removing the controller directive:
when('/', {
templateUrl: 'partial.html'
}).
So, there was no need to specify a controller unless it's a different controller than the one the ng-view is inside of. In your case, that was not the case (you only used a controller that the view is already in) and it was causing two different controllers/scopes (even more if the href attribute is present in the anchor when you click it) to spawn and $scope.datas
in one scope is not the $scope.datas
in the scope that was bound to the partial.
A different variable name would work because of the scope parent/child inheritance; so if the variable names don't match, a parent scope variable would be available in the child scope without specific definition.
Here is the working version: http://plnkr.co/edit/QWPFAakvNEdJzU50LKSx?p=preview
Upvotes: 2
Reputation: 6298
You forgot to inject the $http
in your controller:
app.controller("MyController", function($scope, $http) {
Take a look at this one: var name changed plnkr.
Upvotes: 2