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 ?
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
Related
I really dont know what I am doing wrong ...but my app.get function doesn t work ..when I try to look at networking in Chrome ..there was a HTTP status 302 Found ..but its never go into that function on server side ..I really dont know what I am doing wrong ..help please. .or ask more information I dont know what should be the important ..
Here is my server.js function :
app.get('/api/tests/:id', function(req, res, next) {
console.log('get tests id')
console.log(req.params.id)
Test.findById(req.params.id, function(err, test) {
if (err) return next(err);
console.log(test)
res.send(test);
});
});
here is app.js Angular rouiting ..
.when('/tests/:id',{
templateUrl: 'templates/testView.html',
controller: 'TestViewCtrl'
})
.otherwise({
redirectTo: '/'
});
here is my HTML menu.html file ..where I want to go on that specific address:
<div ng-repeat="test in tests">
<div>
{{test.testName}}
</div>
</div>
..in controller menu.html I´ve got post method because GET method too doesnt work ..
$scope.getTests = function () {
$http.post('/api/getTestText')
.success(function (data) {
$scope.tests = data;
and in detail page for each test is my HTML till now blank ..but in Controller I have something like this :
.controller('TestViewCtrl', ['$scope', '$http','$routeParams','Test', function ($scope, $http, $routeParams, Test) {
Test.get({_id: $routeParams.id},function(test){
$scope.test=test;
console.log($scope.test)
and test factory.js :
.factory('Test', ['$resource', function ($resource) {
return $resource('/api/tests/:id');
}]);
I dont think so that the problem is in front-End side ..but maybe is ..
I heard something about postman app from google chrome apps ...but when I type there my HTTP call ..
localhost:3000/api/tests/ and as params I set _id and IDvalue as value ..the result is same like when I do it by click on menu Item ..
localhost:3000/api/tests?id=5726aa164a26bbe4180700ea
But console.log no working in the server.js side ..so it never goes into app.get() I think...
You need to map the _id field from the body into :id in the url param.
To achieve this, change this:
.factory('Test', ['$resource', function ($resource) {
return $resource('/api/tests/:id');
}]);
Into:
.factory('Test', ['$resource', function ($resource) {
//This plugs in the _id field from the body and injects it into the url param.
//This is an example with mongodb default _id field assuming that's what you use.
return $resource('/api/tests/:id', {id: '#_id'});
}]);
I am working on an application that photographers can use to upload photos. The frontend is AngularJS and there is a RESTfull api backend.
Because of some issues and the fact that ui-router seems better then ngRouter, I decided to change the $routeprovider to $stateProvider of ui-router.
However, my resolve doesn't work anymore (I guessed it would break but I cannot find the solution to my situation).
So here is the original $routeprovider code:
.when('/photographer', {
templateUrl : '/static/partials/photographer/photographer_dash.html',
controller : 'photographerController',
resolve: {
photogPrepService: function (PhotogService) {
return PhotogService.ownPhotos();
}
}
})
The PhotogService is a $resource service that has the following $resource objects:
return $resource(apiHost, {}, {
'ownPhotos': {
url: apiHost + '/photographer_own_photos/',
method: 'GET',
interceptor: ResponseInterceptor
}
});
In the controller I would then do the following (photogPrepService being injected because of the resolve):
var promise = photogPrepService;
promise.then(
function (data) {
$scope.ownPhotos = data.data.photos;
});
This all worked well and I would get the photos in the scope.
However as said with ui-router it doesn't work and I cannot seem to get it working...
According to the docs (https://github.com/angular-ui/ui-router/wiki#resolve) the following should work:
$stateProvider.state('photographer',
{
url: '/photographer',
templateUrl: '/static/partials/photographer/photographer_dash.html',
controller: 'photographerController',
resolve: {
photogPrepService: function (PhotogService) {
return PhotogService.ownPhotos();
}
}
However, when the resolve is injected in the controller and I use console.log() to print the response, I get the following:
Resource(value)
I somehow cannot seem to get the values (JSON response {"photos": ...}) injected into the controller.. I tried various solutions that have been suggested here on stackoverflow and read guides and the API of ui-router, but I cannot wrap my head around what is going wrong... I hope someone can guide me in the right direction..
Thanks!
I think you can use the code below:
//the PhotogService will keep the same as before
//inject the 'PhotogService' into the controller photographerController
PhotogService.ownPhotos().then(function(data) {
$scope.ownPhotos = data.data.photos;
});
//instead of injecting the photogPrepService through 'resove', inject the PhotogService into the controller
//for the $stateProvider
$stateProvider.state('photographer',
{
url: '/photographer',
templateUrl: '/static/partials/photographer/photographer_dash.html',
controller: 'photographerController',
}
You need to give a promise to the resolve, your ressource should look more like :
$stateProvider.state('photographer',
{
url: '/photographer',
templateUrl: '/static/partials/photographer/photographer_dash.html',
controller: 'photographerController',
resolve: {
photogPrepService: function (PhotogService) {
return PhotogService.ownPhotos().$promise;
}
}
});
Or modify your ressources to make them promises.
I am trying to get the query parameters from my angular UI router application. However I cannot seem to get them when I use the query method. The state params are always coming through as undefined.
$stateProvider.state("message",
{
views: {
"main-view": {
templateUrl: "admin/templates/message.html",
controller: ["$scope", "$stateParams", function ($scope, $stateParams )
{
// Get the params
$scope.message = $stateParams.message; // undefined
$scope.error = $stateParams.status; // undefined
}]
}
},
url: "/admin/message?message&status"
})
}
The URL i am using to access this state is:
http://localhost:8080/admin/message?message=hello&status=error
However if I use the Basic Parameters method it works fine. I.e:
url: "/admin/message/:message/:status"
...
http://localhost:8080/admin/message/hello/error
I have html5 mode activated (not sure if that affects it?)
My code has been simplified for the above - am I doing something wrong here? Have I forgot to include anything?
Thanks
This might be a beginner question, but I am retrieving data via http calls in AngularJS and setting them as properties in the $scope variable. However, since http calls take a while, my page tries to load AngularJS more than once in order to render different parts of the page as more the data is retrieved. Is there a way around this? (to hold off on loading the page before all data has been retrieved)
What you could do is to use ng-hide or ng-cloak, so that whatever should not be displayed until the http call fully loaded the data would remain hidden.
take a look at the resolve property in the route settings. If you set something to be resolved the router will resolve this before going to the controller.
app.config(function ($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: "app.html",
controller: "AppCtrl"
resolve: {
app: function ($q, $timeout) {
YourFactory.getData({});
}
}
}
)
});
then create a Factory that will get the data you need
app.factory('YourFactory', ['$http', '$q',
function($http, $q) {
var url = '/api2.php/api';
var YourFactory = {};
var factory_data = [];
var messages = [];
YourFactory.getData = function(params) {
console.log("into GET data");
var deferred = $q.defer();
$http.get(url).success(function(response) {
angular.copy(factory_data, response.data);
deferred.resolve();
}).error(function(response) {
//couldn't resolve therefore it's rejected
deferred.reject();
});
//returns a promise that indicates that something is being resolved and will be returned for the app to continue
return deferred.promise;
};
YourFactory.data = function() {
return factory_data;
};
return YourFactory;
}
]);
then in your controller you need to input the factory and set the scope data from the Factory. Remember that Angular used the Factory to get data before the controller using the resolve property.
app.controller("AppCtrl", ['$scope','YourFactory',
function($scope, YourFactory) {
$scope.data = YourFactory.data();
});
(I haven't tested the code, I simply wrote an example based on an app that I'am doing and in which I passed through the same things as you)
Look at this links if you have any doubt.
https://egghead.io/lessons/angularjs-resolve
http://www.javierlerones.com/2013/07/preloading-data-using-deferred-promises-in-angular-js.html
I've got what I think is a scoping issue with angular ui-router, but I'm not quite sure.
angular.module('Meeting').controller('MeetingController', ['$scope', 'signalRService', '$stateParams', function ($scope, signalRService, $stateParams) {
$scope.setMeetings = function(meetings) {
$scope.meetings = meetings.map(function(meeting) {
return {
id: meeting.CategoryId,
name: meeting.MeetingName
};
});
$scope.$apply();
};
$scope.connectToSignalR = function () {
signalRService.connect();
signalRService.registerAddMeetingsClientMethod($scope.addMeetings);
};
$scope.requestMeetings = function() {
signalRService.requestMeetings($stateParams.departmentId);
};
$scope.connectToSignalR();
$scope.eventId = $stateParams.eventId;
}]);
Basically, my module is injected with a signalR service, and I register a callback on it to set meetings. I have a button on my view to tell the signalR service to fetch the meetings, which then calls the callback I just registered.
Now, all this works fine with ui-router, but only the first time the page is loaded. Here's my routing config:
angular.module('Meeting')
.config(
['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state("meeting",
{
url: "/meeting/:departmentId/",
templateUrl: '/home/meetingPage',
controller: "MeetingController"
})
.state("meeting.members",
{
url: "/members/",
templateUrl: "/home/memberspage",
controller: "MeetingMemberController"
})
.state("meeting.edit", {
url: "/meetingedit",
views: {
'meetingtime': {
templateUrl: '/home/timepage',
controller: 'MeetingTimeController'
},
'location': {
templateUrl: '/home/locationpage',
controller: 'MeetingLocationController'
}
}
});
}]);
When I load up a meeting state (i.e. mysite/meeting/3), all the signalR methods are called, the meeting model in the MeetingController is populated, and the data appears in the view.
When I navigate to another state (i.e. mysite/meeting/4), the signalR methods are still called, and the meeting model is populated, but then just disappears. If I manually refresh the page with F5, it starts to work again, but navigating to a different page stops everything working.
I'm thinking it's a scoping issue, because when I navigate to a different page, the meetings object is still populated from the previous page.
The way I was registering callbacks with a singleton signalR service was getting really cumbersome, and doesn't play well with ui-router, as I found out.
I switched to using promises, and everything works so much more elegantly. Basically, I have a method on my signalR hub that returns the object I want:
public List<Meeting> GetMeetingsForMember(int memberId)
{
return _meetingRepository.GetAllUpcomingMeetingsForMember(int memberId);
}
Then, in my controller, I create a promise, and pass it to my signalR service for resolution:
var deferred = $q.defer();
deferred.promise.then(
function (meetings) {
setMeetings(meetings);
}
);
signalRService.getMeetingsForMember(memberId, deferred);
The getMeetingsForMember method on my signalR service accepts the promise and resolves it:
getMeetingsForMember = function (memberId, deferred) {
deferred.resolve(signalRService.hub.server.getMeetingsForMember(memberId));
}