I'm going to get some data from server using $http and JSON response. $http.get()
are called after route change. But template are changed before data is downloaded. My goal is:
$scope.init()
(via ng-init="init()"
) in controller which is in my new template, this also initializing get data from serverHow can I do this? My App looks for example:
Javascript:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope, $http) {
$scope.init = function() {
$http({method: 'GET', url: 'http://ip.jsontest.com/'}).success(function(data) {
console.log(data);
$scope.ip = data.ip;
});
}
});
myApp.config(function($routeProvider) {
$routeProvider.when('/link', {
controller: 'MyCtrl',
templateUrl: 'embeded.tpl.html'
});
});
HTML:
<script type="text/ng-template" id="embeded.tpl.html">
<div ng-controller="MyCtrl" ng-init="init()">
Your IP Address is: {{ip}}
</div>
</script>
<div>
<ul>
<li><a href="#/link">change route</a></li>
</ul>
<div ng-view></div>
</div>
You need to resolve data before routing happens, thus, move your $http to config section.
This is good tutorial for that, http://www.thinkster.io/pick/6cmY50Dsyf/angularjs-resolve-conventions
This is config part.
$routeProvider.when('/link', {
controller: 'MyCtrl',
templateUrl: 'embeded.tpl.html',
resolve: {
data: function ($q, $http) {
var deferred = $q.defer();
$http({method: 'GET', url: 'http://ip.jsontest.com/'}).then(function(data) {
deferred.resolve(data);
});
return deferred.promise;
}
}
}
and this is controller part
//`data` is injected from routeProvider after resolved
myApp.controller('MyCtrl', function($scope, $http, data) {
$scope.ip = data.ip
});
I think promise in AngularJS is very important concept for any async. processing. You need to use this technique every time you have callback.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments