Refreshing Resolve Data - Ui Router - angularjs

In ionic I'm resolving my data with the Ui-Router's resolve functionality before the controller is initialized. As of now I don't have to $inject my EventService into the Controller. The EventService's getEvents() method resolves the data before the controller is initialized. Everything works correctly this way, but now i'm trying to implement the Ion Refresher. I could easily refresh my $scope.events array within the controller, bloating the controller itself, because I would have to $inject the EventService into the controller, and that also means that every controller that uses the same data will have to contain logic to handle a refresh. What is the best way refresh the data outside of the controller or is that the best way?
Events State Definition and data resolution
.state('tab.events', {
url: '/events',
views: {
'tab-event': {
templateUrl: 'views/events.html',
controller: 'EventsController',
resolve: {
events: function (EventService) {
return EventService.getEvents(); //resolves data before ctrl initialized
}
}
}
}
})
Events Controller
(function() {
'use strict'
angular
.module('app.events')
.controller('EventsController', EventsController);
EventsController.$inject = ['$scope','events'];
function EventsController ($scope,events) {
$scope.events = events;
}
}
)();
Bloated Events Controller - Example
(function() {
'use strict'
angular
.module('app.events')
.controller('EventsController', EventsController);
EventsController.$inject = ['$scope','events','EventsService'];
function EventsController ($scope,events,EventsService) {
$scope.events = events;
$scope.refresh = refresh;
function refresh () {
clearCache(); //pretend method
EventsService.getEvents()
.then(function (events) {
$scope.events = events;
$scope.$broadcast('scroll.refreshComplete');
})
}
}
}
)();
Rather than bloating the controller can I refresh this data another way?

call $state.reload() which is an alias for:
$state.transitionTo($state.current, $stateParams, {
reload: true, inherit: false, notify: true
});
This will cause all your states to be "re-entered" which fetches the resolves and re-initializes the controllers.

I wish a hard refresh, which is basically what a $state.reload() does wasn't the answer. I too have this issue and would rather be able to call some method that just forces all the resolved data objects to rerun. The reload causes a page refresh, which causes nasty UI artifacts.

Related

AngularJS ui-router - view disappears on reload

Recently I started to use ui-router to manage my page status.
I noticed that when I run the server for the first time, the content is there but if I navigate through the pages or reload the page the contents disappears.
I'm aware there was a bug on ui-router that could be causing this. I updated ui-router however the error still persists.
Did anyone manage to find a fix or work around it?
Edit ----
My investigation has lead me to believe that it has nothing to do with the ui-router and more on the time the app takes to complete the promise. As I will get Violation warnings on the setTimeout as part of jQuery
So I was partially right on my last edit hence this answer; jQuery had something to do with my problem (through the use of promises to retrieve data), however it had also to do with how the ui-router works:
As the page content is loaded, ui-router will manage the first load (and subsequent reloads) with the data that is provided by the GET request.
As this is a promise it is not guaranteed (especially as you grow your DB) that the data will be there in time to render the page.
To avoid from happening use the resolve property as part of ngRoute. This property allows for all the necessary data to be loaded before rendering the DOM.
If you want to read more about follow the link below:
https://medium.com/opinionated-angularjs/advanced-routing-and-resolves-a2fcbf874a1c
My code below:
App.js
'use strict';
angular
.module('knoweeApp', ['ui.router'])
.config(['$stateProvider','$urlRouterProvider',function($stateProvider,$urlRouterProvider) {
$stateProvider
.state('home', {
url:'/',
templateUrl: 'views/user.html',
controller: 'UserCtrl as user',
resolve: {
user: function(userFinder) {
return userFinder.getUsers();
}
}
})
.state('teacher', {
url:'/teacher/:name',
templateUrl: 'views/teacher.html',
controller: 'TeacherCtrl as teacher'
});
$urlRouterProvider.otherwise('/');
}]);
Service: userFinder
'use strict';
/**
* #ngdoc service
* #name knoweeApp.userFinder
* #description
* # userFinder
* Service in the knoweeApp.
*/
angular.module('knoweeApp')
.service('userFinder', function () {
// AngularJS will instantiate a singleton by calling "new" on this function
this.getUsers = function (){
return $.get('users.json');
};
});
Controller: UserCtrl
'use strict';
angular.module('knoweeApp')
.controller('UserCtrl', function (userFinder,user) {
this.teachers = user;
this.increment = function (item) {
item.rating += 1;
};
this.decrement = function (item) {
item.rating -= 1;
};
});
Hope this helps, contact me if in doubt

Set AngularJS Global before App Initialization

I am currently working in an AngularJS code base where different routes are triggered depending on some toggle element attached to every customer. In my app, I need to route to different places twice, once, in my app.js file, where I manage my state and another time, in a controller when I use the same variable to branch.
I have tried to use a combination of manually bootstrapping and using the run method but haven't had any success.
var app = angular
.module('app', ['customer'])
.run(function (customer) {
angular.element(document).ready(function () {
customer.myMethod().then(function (enabled) {
enabled = enabled;
angular.bootstrap(document, ['app']);
});
});
});
$stateProvider
.state('home', {
url: enabled ? '/' : '/customer',
templateUrl: 'views/home.html',
controller: 'HomeCtrl',
data: {
title: 'Home'
}
})
And then in my controller, use the same variable in my init method for example:
$scope.init = function () {
if (enabled) { ... }
else { ... }
}
$scope.init();
I notice that the enabled variable eventually does get set, but it happens after the state is decided. Is there a way to set a global variable before my AngularJS app starts in order to use it anywhere?
Thanks

AngularJS UI-Router Access $stateParams from State's data object

Given the following state in ui-router:
.state('some.state', {
url: '/some/:viewType',
templateUrl: 'myTemplate.html',
controller: 'SomeStateController',
controllerAs: 'vm',
data: {
authorizedFor: [SOME_ROLE]
}
}
I'm trying to use the "data" object for a state to help control access to authorized states. Separately, I handle the $stateChangeStart event to look at data.authorizedFor and act accordingly.
The problem, though, is that the list of authorized roles might change based on the value of :viewType. I thought I could let data:{} be a function, inject $stateParams, and handle the logic there...but that won't do.
So, I tried using the params object instead, but at the $stateChangeStart time, the :viewType is not yet accessible from $state.params or $stateParams.
Stepping through in dev tools, I noticed that $state.transitionTo.arguments is populated, but it seems awfully hacky to go that route.
params: {
authorizedFor: function($state) {
console.log($state.transitionTo.arguments[1].viewType); // has value I need
}
}
Any suggestions?
My suggestion is to use resolve to provide your controller with content or data that is custom to the state. resolve is an optional map of dependencies which should be injected into the controller.
If any of these dependencies are promises, they will be resolved and converted to a value before the controller is instantiated and the $stateChangeSuccess event is fired.
for example:
$stateProvider
.state('profile', {
url: '/profile',
templateUrl: 'profile.html',
resolve:{
'ProfileService': function(ProfileService){
return ProfileService.promise_skillRecommendation_mock;
}
}
})
The profileService code:
var app = angular.module('app').service("ProfileService", function($http){
var myData = null;
var promise_skillRecommendation_mock =
$http.get('Mock/skillRecommendation-mock.json')
.success(function(data){
myData = data;
});
return{
promise_skillRecommendation_mock: promise_skillRecommendation_mock,
get_skillRecommendation: function(){
return myData;
}
};
});
and the controller code which will use this service is:
angular.module('app').controller('ProfileController', function($scope, $http, ProfileService){
$scope.skillRecommendation = ProfileService.get_skillRecommendation();
The object in resolve below must be resolved (via deferred.resolve() if they are a promise) before the controller is instantiated. Notice how each resolve object is injected as a parameter into the controller.
by using this code, the page will be displayed only after that the promise will be resolved.
for more info please view this page: https://github.com/angular-ui/ui-router/wiki

AngularJS watch value within service

I'm currently developing an AngularJS web application.
I have a primary view (Index), child view (Dashboard) and grandchild view (Raiding The Rails).
http://localhost:4000/#/dashboard/raiding-the-rails/1
Within the grandchild view (Raiding The Rails) I am displaying dress information relevant to the state ID /1, each dress has a specified state ID e.g /1,/2,/3.
I have a controller/service sending the state ID to a console.log (within the parent) and when viewing raiding-the-rails/1 the console.log displays {stateID: "1"}, If I change the URL to raiding-the-rails/4 the console.log doesn't update unless I refresh the page.
Also, When I completely refresh the browser the console.log spits out three objects instead of one?
I've reviewed many sites and have tried and tried again trying to figure this out, I even tried setting up a Watch service but this failed massively.
If anyone could help me out I would be highly grateful!Thank you.
App:
(function(angular, undefined){
"use strict";
var am = angular.module('virtual-fitting', ['ui.router']);
am.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('dashboard', {
url: '/dashboard',
templateUrl: '../views/dashboard.html'
})
.state('dashboard.raidingtherails', {
url: '/raiding-the-rails',
templateUrl: '../views/dashboard.raiding-the-rails.html'
})
.state('dashboard.raidingtherails.dress', {
url: '/:id',
templateUrl: '../views/dashboard.raiding-the-rails.dress.html'
});
$urlRouterProvider.otherwise('/');
});
})(angular);
Service:
(function(angular, undefined) {
"use strict";
var am = angular.module('virtual-fitting');
am.factory('raidingService', function () {
var raidingService = {
stateID: null
};
return raidingService;
});
})(angular);
Parent Controller:
(function(angular, undefined) {
"use strict";
var am = angular.module('virtual-fitting');
am.controller('dashboardCtrl', function(raidingService) {
console.log(raidingService);
});
})(angular);
Child Controller:
(function(angular, undefined) {
"use strict";
var am = angular.module('virtual-fitting');
am.controller('raidingtherailsCtrl', function($state, $stateParams, raidingService) {
var self = this;
raidingService.stateID = $stateParams.id;
});
})(angular);
I assume it's in the parent controller that you want to watch your service?
If so, you could watch a function, like so:
$scope.$watch(function() {
return raidingService.stateId;
}, function(value) {
console.log(value);
}, true);
That should work.
MVC pattern used in any framework:
You creating Service with .get() and .set() methods. Set method is common to be used in any place you desire to operate model value and allows you to create one point that will handle changes to your model. The final move in .set() method is .$boradcast() notifying whole application about changes to your model.
Pros:
one access point to value
application is know about any changes
no need to write $watch with watching collections (holly-molly)
having access point to changes with '$on' in your controllers $scope
Cons:
easy to forget to use .set() method instead of simple assignment

AngularJS UI-Router scoping issues

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));
}

Resources