How I can add jquery-ui.js to my controller.I'm new to the ui-router
.state('new_patient', {
url: '/newpatient',
templateUrl: window.localStorage.getItem('contextPath') + '/module/laboratory/newpatient',
controller: 'PatientController',
resolve: {
deps: function($q, $rootScope) {
var deferred = $q.defer();
var dependencies = ['jquery-ui'];
require(dependencies, function() {
$rootScope.$apply(function() {
deferred.resolve();
});
});
return deferred.promise;
}
}
});
OR as follows
resolve: { async: ['jquery-ui', function($) {
}]
}
pls help..
Its for working of an accordion.. Thanks in advance for replies.
.state('new_patient', {
url: '/newpatient',
templateUrl: window.localStorage.getItem('contextPath') + '/module/laboratory/newpatient',
controller: 'PatientController',
resolve: {
deps: function ($q){
var defer = $q.defer();
require(['js/core/jquery-ui'], function() {
defer.resolve();
});
return defer.promise;
}
}
});
Related
I'm facing problem while initializing a third party JavaScript API (iHUB) inside RUN method of AngularJS. Currently the code is behaving in asynchronous mode. I want IHUB to first initialize and then AngularJS route/controller should get called. (Is it possible to make utilization of the callback method provided by IHUB ?)
var nameApp = angular.module('nameApp', ['ngRoute']);
nameApp.run(['$window', 'myService', function($window, myService) {
//initialize IHUB
var actuate= new actuate();
actuate.initialize('http://localhost:8700/iportal', settings.reqOps, "user", "pwd", callback);
function callback(){
alert('started!!');
}
}]);
nameApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/:tabname', {
templateUrl: 'pages/analyticsDetail.html',
controller: 'tabDetailCtrl'
}).
when('/:tabname/:reportName', {
templateUrl: 'pages/analyticsDetail.html',
controller: 'reportDetailCtrl'
}).
otherwise({
redirectTo: '/Buy Side Dashboard'
});
}]);
There is only one way to achieve a "real" before AngularJS initialization behavior by using angular.bootstrap();. This allows you to initialize your AngularJS application manually.
Note: You should not use the ng-app directive when manually bootstrapping your app.
> Fiddle demo
View
<div ng-controller="MyController">
Hello, {{greetMe}}!
</div>
Application
angular.module('myApp', [])
.controller('MyController', ['$scope', function ($scope) {
$scope.greetMe = 'World';
}]);
var actuateDummy = {
initialize: function (callback) {
setTimeout(callback, 2500);
}
};
actuateDummy.initialize(function () {
angular.element(function() {
angular.bootstrap(document, ['myApp']);
});
})
This is an other approach which uses the resolve state of ui-router. This service only initializes iHUB if it not has been initialized yet:
This service also returns the actuate object. In that way you can use it in your controller or components after init.
> Demo fiddle
View
<nav>
<a ui-sref="state1">State 1</a>
<a ui-sref="state2">State 2</a>
</nav>
<div ui-view></div>
AngularJS Application
var myApp = angular.module("myApp", ["ui.router"]);
myApp.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state("state1", {
url: "#",
template: "<p>State 1</p>",
controller: "Ctrl1",
resolve: {
iHubInit: function(iHubService) {
return iHubService.init()
}
}
}).state("state2", {
url: "#",
template: "<p>State 2</p>",
controller: "Ctrl2",
resolve: {
iHubInit: function(iHubService) {
return iHubService.init()
}
}
});
});
myApp.controller("Ctrl1", function($scope, iHubService) {
console.log("Ctrl1 loaded.");
});
myApp.controller("Ctrl2", function($scope, iHubService) {
console.log("Ctrl2 loaded.");
});
myApp.service('iHubService', ["$q", function($q) {
this.iHubServiceInitialized = false;
this.actuate = null;
this.init = function() {
if (!this.iHubServiceInitialized) {
//Init
var self = this;
var deferred = $q.defer();
this.actuate = new actuate();
//initialize
this.actuate.initialize('http://localhost:8700/iportal', settings.reqOps, "user", "pwd", function() {
self.iHubServiceInitialized = true;
deferred.resolve(self.actuate);
});
return deferred.promise;
} else {
return this.actuate;
}
}
}]);
Try to add a resolve attribute when configuring your route provider like below:
var nameApp = angular.module('nameApp', ['ngRoute']);
nameApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/:tabname', {
templateUrl: 'pages/analyticsDetail.html',
controller: 'tabDetailCtrl',
resolve: {
ihubInit: ['iHubService', function (iHubService) {
return iHubService.init();
}]
}
}).
when('/:tabname/:reportName', {
templateUrl: 'pages/analyticsDetail.html',
controller: 'reportDetailCtrl',
resolve: {
ihubInit: ['iHubService', function (iHubService) {
return iHubService.init();
}]
}
}).
otherwise({
redirectTo: '/Buy Side Dashboard'
});
}]);
nameApp.service('iHubService', ["$q", function($q){
this.init = function() {
var deferred = $q.defer();
var actuate= new actuate();
actuate.initialize('http://localhost:8700/iportal', settings.reqOps, "user", "pwd", callback);
function callback(){
deferred.resolve();
}
return deferred.promise;
}
}]);
I am new in require.js, I am implementing requier.js with angular.js, but i got error. Here is my code:
config file:
require.config({
paths: {
angular: 'https://code.angularjs.org/1.5.5/angular.min',
angularRoute: '//rawgit.com/angular-ui/ui-router/0.2.15/release/angular-ui-router.min',
angularAnimate: '//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min',
},
shim: {
'angular' : {'exports' : 'angular'},
'angularRoute': ['angular'],
'angularAnimate': ['angular']
},
priority: [
"angular"
],
});
require([
'angular',
'app',
'controllers/first-controller',
'controllers/second-controller',
'controllers/third-controller',
'services/services',
'directives/directives'
], function(angular, app) {
var $html = angular.element(document.getElementsByTagName('html')[0]);
angular.element().ready(function() {
// bootstrap the app manually
angular.bootstrap(document, ['WalletHubApp']);
});
}
);
This is my app file:
define(['angular'], function (angular) {
var app = angular.module('app', ['ui.router','ngAnimate']);
WalletHubApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/walletHub/1/');
$stateProvider
.state('test', {
url: '/walletHub/:id/{folderPath:[a-zA-Z0-9/]*}',
templateUrl: function ($stateParams){
return "templates/"+$stateParams.id + '.html';
},
controllerProvider: function($stateParams) {
console.log($stateParams)
var ctrlName = $stateParams.id + "Controller";
return ctrlName;
}
});
});
return app;
});
This is Controller File:
define(['app'], function(app) {
WalletHubApp.controller('1Controller', function ($scope,$stateParams,$stateParams,$state,$http) {
$http.get('sample.json')
.then(function(res){
$scope.persons = res.data
});
var parts = $stateParams.folderPath.split('/')
$scope.params = false;
if(parts[0] != "")
{
$scope.parts = parts;
$scope.params = true;
}
})
return;
});
I dont know what is wrong in this code.Please help me to sort out this
According to official document
It is normally best to avoid coding in a name for the module and just let the optimization tool burn in the module names.
// in app.js file, remove module name :
define(["angular", "angularRoute","angularAnimate"], function(angular) {
var WalletHubApp = angular.module('WalletHubApp', ['ui.router','ngAnimate']);
WalletHubApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/walletHub/1/');
$stateProvider
.state('test', {
url: '/walletHub/:id/{folderPath:[a-zA-Z0-9/]*}',
templateUrl: function ($stateParams){
return "templates/"+$stateParams.id + '.html';
},
controllerProvider: function($stateParams) {
console.log($stateParams)
var ctrlName = $stateParams.id + "Controller";
return ctrlName;
}
});
});
return WalletHubApp;
});
// in controller file change WalletHubApp to app
define(['app'], function(WalletHubApp) {
WalletHubApp.controller('1Controller', function ($scope,$stateParams,$stateParams,$state,$http) {
$http.get('sample.json')
.then(function(res){
$scope.persons = res.data
});
var parts = $stateParams.folderPath.split('/')
$scope.params = false;
if(parts[0] != "")
{
$scope.parts = parts;
$scope.params = true;
}
})
return;
});
I'm having trouble figuring out how I could pass a parameter to a function that is a part of resolve of ngRoute.
In my case I'm doing stuff with tokens. These tokens are typed, so you cannot use the same token for confirming and email and reseting a password. Here's how my routes are defined:
.when("/confirm/:token", {
controller: "confirmEmailController",
templateUrl: "/app/views/confirmEmail.html",
resolve: {
tokenStatus: getTokenStatus
}
})
.when("/reset/:token", {
controller: "resetPasswordController",
templateUrl: "/app/views/resetPasswordEmail.html",
resolve: {
tokenStatus: getTokenStatus
}
})
Here's the getTokenStatus function that's being called for both of them:
var getTokenStatus = ["$q", "$route", "tokenService", function($q, $route, tokenService)
{
var deferred = $q.defer();
var tokenType = ???? //<-- how do I pass this?
tokenService
.getTokenStatus($route.current.params.token, tokenType)
.success(function(response)
{
deferred.resolve(true);
})
.error(function()
{
deferred.resolve(false);
});
return deferred.promise;
}];
The problem is that in order to avoid code duplication I need to somehow pass the value of the token type, as marked in the code. How could I do that?
I've been messing about with this for the last 2 hours, but can't seem to figure it out.
1. You can try to include token type into route
.when("/:tokenType/:token", {
controller: "confirmEmailController",
templateUrl: "/app/views/confirmEmail.html",
resolve: {
tokenStatus: getTokenStatus
}
})
.when("/:tokenType/:token", {
controller: "resetPasswordController",
templateUrl: "/app/views/resetPasswordEmail.html",
resolve: {
tokenStatus: getTokenStatus
}
})
And then just get it from $route.current.params.tokenType. But it's not clean solution - you should check your URL for validity.
2. You can use function wrapping
$routeProvider.when("/confirm/:token", {
controller: "confirmEmailController",
templateUrl: "/app/views/confirmEmail.html",
resolve: {
tokenStatus: getTokenStatus("confirm")
}
})
.when("/reset/:token", {
controller: "resetPasswordController",
templateUrl: "/app/views/resetPasswordEmail.html",
resolve: {
tokenStatus: getTokenStatus("reset")
}
});
var getTokenStatus = function(tokenType) {
return ["$q", "$route", "tokenService", function($q, $route, tokenService) {
var deferred = $q.defer();
tokenService
.getTokenStatus($route.current.params.token, tokenType)
.success(function(response)
{
deferred.resolve(true);
})
.error(function()
{
deferred.resolve(false);
});
return deferred.promise;
}];
};
3. You can move get-token-status logic into separate servise
$routeProvider.when("/confirm/:token", {
controller: "confirmEmailController",
templateUrl: "/app/views/confirmEmail.html",
resolve: {
tokenStatus: ['tokenStatusGetterService', function(tokenStatusGetterService){
return tokenStatusGetterService("confirm");
}]
}
})
.when("/reset/:token", {
controller: "resetPasswordController",
templateUrl: "/app/views/resetPasswordEmail.html",
resolve: {
tokenStatus: ['tokenStatusGetterService', function(tokenStatusGetterService){
return tokenStatusGetterService("reset");
}]
}
});
//...
.service('tokenStatusGetterService', ["$q", "$route", "tokenService", function($q, $route, tokenService) {
return function(tokenType) {
var deferred = $q.defer();
tokenService
.getTokenStatus($route.current.params.token, tokenType)
.success(function(response)
{
deferred.resolve(true);
})
.error(function()
{
deferred.resolve(false);
});
return deferred.promise;
};
}]);
one way to do it is to put a function on your getTokenStatus service.
this is a simplified example, yet it shows how to pass an argument to your resolve function.
app.factory('getTokenStatus',['$q', '$timeout', '$route', function($q, $timeout, $route){
this.action = function(tokenType) {
var defer = $q.defer();
$timeout(function(){
var res = {
path: $route.current.params.token,
tokenType: tokenType
}
defer.resolve(res);
},1000);
return defer.promise;
}
return this;
}]);
and call it from your resolve object:
app.config(function($routeProvider){
$routeProvider
.when("/123/:token", {
template: "<h1>hello</h1>",
controller: 'testCtrl',
resolve: {
tokenStatus: function(getTokenStatus) {
return getTokenStatus.action('firstToken').then(function(res){
console.log(res);
});
}
}
})
here's a plnkr
I am trying to create a login script using Angularjs. I have an Authentication Service that handles the logic for that.
Here the service:
.factory("AuthSvc",
['$http','$q','$state',
function ($http,$q,$state) {
function GetUser() {
var d = $q.defer();
$http.get('api/auth/check')
.success(function(res){
d.resolve(res);
});
return d.promise;
};
return {
login: function (credentials, form) {
var defer = $q.defer();
$http.post('/api/auth/login', credentials)
.success(function (response) {
form.$setPristine();
user = response;
$state.go('base.posts.content');
defer.resolve();
})
.error(function (response) {
defer.reject();
});
return defer.promise;
},
isLoggedIn: GetUser,
user: null
};
}]);
I have a resolve property and a listener for the user property to update the view on the app configuration as below:
.config(['$stateProvider',
function ($stateProvider) {
// Now set up the states
$stateProvider
.state('base', {
url : "",
templateUrl: "/templates/base/index.html",
resolve : {user : ["AuthSvc",
function(AuthSvc) {
return AuthSvc.user;
}]
},
})
.state('base.login', {
url : "login",
templateUrl: "/templates/login/index.html",
controller : 'LoginCtrl'
})
.state('base.posts', {
abstract : true,
url : 'posts',
templateUrl: '/templates/posts/posts.html'
})
.state('base.posts.content',{
url: '',
resolve: {
posts: function (PostsSvc) {
return PostsSvc.getPosts();
}
},
views:{
'create': {
templateUrl: '/templates/posts/create.html',
controller: 'PostsCtrl'
},
'list': {
templateUrl: '/templates/posts/list.html',
controller: 'PostsCtrl'
}
}
});
}]);
app.run(['$rootScope','AuthSvc','$state',
function ($rootScope,AuthSvc,$state,
) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$rootScope.$on('$stateChangeStart',
function(event, next, current){
AuthSvc.user = AuthSvc.isLoggedIn();
});
$state.transitionTo('base.posts.content');
}]);
}());
The $rootScope.on('$stateChangeStart') is not working. I see some code where people directly assign a value to a promise without using the then function of the promise. How do I accomplish this using this code?
In my HTML, I have the following two links, but when I click them or try to enter them into the browser, my new ui-router code is redirecting them to the otherwise url I have specified. Why is this?
Folders
Clients
//Setting up route
window.app.config(function($stateProvider, $urlRouterProvider) {
// For any unmatched url, redirect to "/"
$urlRouterProvider.otherwise("/asfasfsa");
// Now set up the states
$stateProvider
.state('root', {
url: "/",
templateUrl: 'views/index.html',
resolve: { factory: setRoot }
})
.state('dashboard', {
url: "/dashboard",
templateUrl: 'views/dashboard/dashboard.html',
resolve: { factory: checkAuthentication }
})
.state('folders-show', {
url: "/folders/:folderId'",
templateUrl: 'views/dashboard/folders/view.html',
resolve: { factory: checkAuthentication }
})
.state('clients-list', {
url: "/clients'",
templateUrl: 'views/clients/list.html',
resolve: { factory: checkAuthentication }
})
});
// Check if user is logged in
var checkAuthentication = function ($q, $location) {
if (window.user) {
console.log(window.user);
return true;
} else {
console.log("Not logged in...")
var defered = $q.defer();
defered.reject();
$location.path("/");
return defered.promise;
}
};
// Set Root URLs
var setRoot = function ($q, $location) {
if (window.user) {
var defered = $q.defer();
defered.reject();
$location.path("/dashboard");
return defered.promise;
} else {
return true;
}
};
// Setting HTML5 Location Mode
window.app.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix("!");
}
]);
Sorry, simple typos on the folder and clients urls were causing the issue.
Foiled by typos again!