Sharjil Khan Sharjil Khan - 1 month ago 17
AngularJS Question

Controller is not getting call when its state is changing

I am using ui-router for routing my angular app. I have set the routing configuration but didn't want to use controller as syntax. I am using following syntax:

.state('blog',{
url: '/blog',
templateUrl: '/templates/blog.html',
controller: 'BlogController'
})


However the template is being called into my ui-view but I BlogController is not being called. I have used console.log() into my BlogController but I didn't see anything in my console. Here is my BlogController.js

app.controller('BlogController', function($scope, PostService,){
console.log(0);
PostService.getPost().then(function(post){
$scope.postModel = post;
});
console.log(1);
});


As you can see, I am using a service to call data using $http. Below is my PostService :

app.service('PostService', function ($http) {

this.getPost = function () {
return $http({
method : 'GET',
url : 'http://domain.com/wp-json/wp/v2/posts'
})
.then(function(response){
return response.data;
}, function(error){
return error;
});
};
});


I think this the problem related to the service call. I have read some post about resolve property in state method of ui-router. I have tried that but nothing has working. Can somebody please help me to get rid out of this ?

Answer

The declaration of the ui-router module is wrong

var app = angular.module('mySiteApp', [require('angular-ui-router')])

Should be,

var app = angular.module('mySiteApp', ['ui.router'])

Check this link for cors errors