I want to add optional $stateParams to below $state ,Lets say currently i have processId and i want to add assessmentId as optional params. My goal is to launch same template and controller from two places in application and it will launch based on $stateParams.
How can i achieve that task ?
app.js
Add Challenge
.state('app.addPrcChallenge', {
url: '/add/prcChallenge',
params: { processId: null,assessmentId:null},
templateUrl: 'views/process/processChallenge.html',
controller: 'ProcessChallengesCtrl',
data: {
authenticate: true
},
resolve: {
existingChallenge: function(){
return null;
},
Edit Challenge
.state('app.editPrcChallenge', {
url: '/edit/prcChallenge/:challengeKey/processId?/:assessmentId?',
templateUrl: 'views/process/processChallenge.html',
controller: 'ProcessChallengesCtrl',
data: {
authenticate: true
},
Directly mention them in the url with a ? suffix for optional params:
.state('app.addPrcChallenge', {
url: '/add/prcChallenge/:processId/:assessmentId?',
templateUrl: 'views/process/processChallenge.html',
controller: 'ProcessChallengesCtrl',
data: {
authenticate: true
},
resolve: {
existingChallenge: function(){
return null;
}
}
});
You can ignore the params property after this change, as the params property is used to define params which do not appear as part of the URL
You URL property should be like this:
.state('app.addPrcChallenge', {
url: '/add/prcChallenge/:processId/:assessmentId?',
templateUrl: 'views/process/processChallenge.html',
controller: 'ProcessChallengesCtrl',
data: {
authenticate: true
},
resolve: {
existingChallenge: function(){
return null;
},
.state('app.addPrcChallenge', {
url: '/add/prcChallenge/:processId/:assessmentId',
templateUrl: 'views/process/processChallenge.html',
controller: 'ProcessChallengesCtrl',
params: {
processId: null,
assessmentId: null
}
data: {
authenticate: true
},
resolve: {
existingChallenge: function(){
return null;
}
}
});
Related
addressbookController :
$http({
method: 'GET',
url: '/api/getnewgroup'
})
.then(function (response) {
$scope.draft.groups = response.data;
$scope.groups = response.data; // updated
}, function (response) {
console.log(response);
});
In this above controller, i am getting json response in $scope.draft.groups, I have this draft object in another controller called profsmsController.
profsmsController :
$scope.draft = {
draftType: '',
scheduledTime: '',
senderdata: '',
draftData: {
contacts: ''
},
groups: {
select: false
},
senderName: '',
message: '',
draftName: '',
createdOn: '',
updatedOn: ''
};
How to access $scope object ?
My Controller:
angular
.module('sampleApp.controllers', [])
//addressbook page controller
.controller('addressbookCtrl', function ($http, $scope, $rootScope, $location,
$state, toastr, $timeout, $window, sharedService) {
// Groups
// get group
$http({
method: 'GET',
url: '/api/getnewgroup'
})
sharedService.getDraftPromise().then(function (response) {
$scope.groups = response.data;
$scope.draft.groups = response.data;
}, function (response) {
console.log('error');
});
})
.controller('profsmsCtrl', function ($http, $scope, $rootScope, $location,
$state, toastr, $timeout, $window) {
/* for drafts */
$scope.draft = {
draftType: '',
scheduledTime: '',
senderdata: '',
draftData: {
contacts: ''
},
groups: {
select: false
},
senderName: '',
message: '',
draftName: '',
createdOn: '',
updatedOn: ''
};
//add draft
$scope.addmanualInputDraft = function () {
$http.post('/api/addmanualinputdraft', $scope.draft).then(function (response) {
toastr.success("Added successfully!");
$('.bd-example-modal-lg-manual').modal('hide');
$state.reload();
});
}
})
My services.js:
angular
.module('sampleApp.services', [])
.factory('sharedService', function ($http) {
var draftPromise = $http({
method: 'GET',
url: '/api/getnewgroup'
});
return {
getDraftPromise: function () {
return draftPromise;
}
};
});
my app.js:
'use strict';
angular
.module('sampleApp', ['sampleApp.controllers', 'sampleApp.directives','sampleApp.services','sampleApp.filters','ui.router','toastr','ngSanitize', 'ui.select'])
.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.hashPrefix('');
$urlRouterProvider.otherwise('/dash');
$stateProvider
.state('dash', {
url: '/dash',
templateUrl: 'partials/dash',
})
.state('quicksms', {
url: '/quicksms',
templateUrl: 'partials/quicksms',
controller: 'quicksmsCtrl'
})
.state('professionalsms', {
url: '/professionalsms',
templateUrl: 'partials/professionalsms',
controller: 'profsmsCtrl'
})
.state('file2sms', {
url: '/file2sms',
templateUrl: 'partials/file2sms',
controller: 'file2smsCtrl'
})
.state('addressbook', {
url: '/addressbook',
templateUrl: 'partials/addressbook',
controller: 'addressbookCtrl'
})
});
This is updated full code. I want to access $scope.draft.groups object from addressbook Controller.
In general, you'd want to create a service that holds your shared data:
myApp.factory('sharedService', function($http) {
var draftPromise = $http({
method: 'GET',
url: '/api/getnewgroup'
});
return {
getDraftPromise: function() {
return draftPromise;
}
};
});
In your controllers, you can then use the service by declaring it as a dependency:
myApp.controller("myController", function($scope, sharedService) {
sharedService.getDraftPromise().then(function(response) {
$scope.draft.groups = response.data;
});
});
Both controllers will refer to the same instance of draftPromise.
Note: if you are minifying your code, you'll want to use the alternate syntax for dependency injection that uses arrays. Take a look at the official documentation for dependency injection.
I created web-application, in which there is a redirect after login to welcome page, but the header is not updated in this case.
Here is my Angular code:
MyApp.controller('LoginController', function ($scope) {
$scope.login = function () {
login();
var name = "";
if (document.cookie.indexOf("name") !== -1)
name = document.cookie.split('=')[2];
$scope.menu = [
{
title: 'Product',
url: 'product'
},
{
title: 'About',
url: 'about'
},
{
title: 'Contact',
url: 'contact'
},
{
title: name,
url: 'welcomeUser'
},
{
title: 'LogOut',
url: 'logout'
}
];
$scope.refresh();
};
});
MyApp.controller('MainController', function ($scope) {
var name = "";
if (document.cookie.indexOf("name") !== -1)
name = document.cookie.split('=')[2];
if (document.cookie.indexOf("name") === -1 && (name === "" || name === undefined)) {
$scope.menu = [
{
title: 'Product',
url: 'product'
},
{
title: 'About',
url: 'about'
},
{
title: 'Contact',
url: 'contact'
},
{
title: 'Register',
url: 'register'
},
{
title: 'Login',
url: 'login'
}
];
} else {
$scope.menu = [
{
title: 'Product',
url: 'product'
},
{
title: 'About',
url: 'about'
},
{
title: 'Contact',
url: 'contact'
},
{
title: name,
url: 'welcomeUser'
},
{
title: 'LogOut',
url: 'logout'
}
];
}
});
Angular config code:
MyApp.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/home', {
templateUrl: 'partials/home.html',
controller: 'MainController'
})
.when('/login', {
templateUrl: 'partials/login.html',
controller: 'LoginController'
})
.otherwise({
redirectTo: '/404'
});
});
And here is my JS code for POST request sending - login user function:
function login() {
var username = document.getElementById('usernameLogin').value;
var password = document.getElementById('passwordLogin').value;
if (!username.trim() || username.length === 0 || !password.trim() || password.length === 0) {
document.getElementById('wrong_username').style.display = 'block';
document.getElementById('wrong_password').style.display = 'block';
return;
}
var json = {
username: username,
password: sha1(password)
};
$.ajax({
type: "POST",
url: "http://localhosts:7777/account_management/login_user",
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data === "true") {
document.cookie = "";
document.cookie = "username=" + username;
window.location.href = "/#/welcomeUser";
} else if (data === "false") {
document.getElementById("wrong_password").style.display = "block";
} else {
alert(data);
};
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
The authorization itself works fine, but $scope.menu updates only after page refresh.
Is there any ideas how to fix it?
MainController ad LoginController are two different controllers and are having different scopes.
Changing $scope.menu in one doesn't change in another as they don't have any parent child relationship.
You must either have the menu in $rootScope and then update it in the respective controllers after login.
MyApp.controller('LoginController', function ($scope, $rootScope) {
$rootScope.menu = [];
});
MyApp.controller('MainController', function ($scope, $rootScope) {
$rootScope.menu = []; // update the menu
});
Else, have it as a service so that you can use $emit event and in it to update the menu once the user has logged in.
The function login() {...} must be part of a service. You must avoid using jQuery in an angular project. Use $http inside service which is preferable and provides same functionality as $.ajax
Instead of having your menu in $rootScope, you could use event to warn your menu that the user has logged in and that he should reload itself.
On LoginController
$rootScope.$broadcast('userLoggedIn');
On MainController
$rootScope.$on('userLoggedIn', function () {
//Code to apply modification to your menu
});
If you have to pass parameters, you can use the second argument of $broadcast method like this :
$rootScope.$broadcast('userLoggedIn', {key: 'value'});
$rootScope.$on('userLoggedIn', function (params) {
console.log(params.key); //value
});
Solution 1 :
You need to use $rooteScope for call scope variables from another controller.
Please use $rooteScope.objectName in your login controller instead of using$scope.objectName.
Like
// Assign the menu details on scope variable in main controller
MyApp.controller('MainController', function ($scope) {
$scope.menu = [
{
title: 'Product',
url: 'product'
},
{
title: 'About',
url: 'about'
},
{
title: 'Contact',
url: 'contact'
},
{
title: 'Register',
url: 'register'
},
{
title: 'Login',
url: 'login'
}
];
});
//then call the scope variables via rootScope from login controller
MyApp.controller('LoginController', function ($scope,$rootScope ) {
$rootScope.menu = [
{
title: 'Product',
url: 'product'
},
{
title: 'About',
url: 'about'
},
{
title: 'Contact',
url: 'contact'
},
{
title: 'Register',
url: 'register'
},
{
title: 'Login',
url: 'login'
}
];
});
Solution 2
Your window.location.href = "/#/welcomeUser"; is a javascript code, So it is not consider the scope objects
You need to change window.location.href = "/#/welcomeUser";
to $location.path('/#/welcomeUser');
also you need to configure the $location on your controller
Solution 3
If above two solutions are not working, you need to manually reload the page by using $route.reload()
But the third solution is not good, because it will make a page reload. But it's solve your issue to manually reload the screen.
I have implemented the small mobile application in Cordova (VS2015). In my application I'm getting all the required data using asp.net wep api. My mobile solution working fine in ripple emulator. But not working in device mode (Andorid). I have published my web service and local IIS server and I use local IP address and port no to access it. Also I have enable cross domain call in my web api too.
bellow is my app.js find and service That I have implement using angularJS.
var app = angular.module('RandBApp', ['ionic', 'RandBApp.controllers'])
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.config(function ($compileProvider, $stateProvider, $urlRouterProvider, $httpProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|ghttps?|ms-appx|x-wmapp0):/);
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|file|ms-appx|x-wmapp0):|data:image\//);
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "app/views/menu.html",
controller: 'RandBAppCtrl'
})
.state('app.products', {
url: "/products",
cache: false,
views: {
'menuContent': {
templateUrl: "app/views/products.html",
controller: 'ProductsCtrl'
}
}
})
.state('app.productdetail', {
url: "/products/:productid",
views: {
'menuContent': {
templateUrl: "app/views/productdetail.html",
controller: 'ProductDetailCtrl'
}
}
})
.state('app.signup', {
url: "/signup",
cache: false,
views: {
'menuContent': {
templateUrl: "app/views/signup.html",
controller: 'SignUpCtrl'
}
}
})
.state('app.reservations', {
url: "/reservations",
cache: false,
views: {
'menuContent': {
templateUrl: "app/views/reservations.html",
controller: 'ReservationsCtrl'
}
}
})
.state('app.reservationdetail', {
url: "/reservations/:reservationid",
views: {
'menuContent': {
templateUrl: "app/views/reservationdetail.html",
controller: 'ReservationDetailCtrl'
}
}
})
.state('app.orders', {
url: "/orders",
cache: false,
views: {
'menuContent': {
templateUrl: "app/views/orders.html",
controller: 'OrdersCtrl'
}
}
})
.state('app.orderdetail', {
url: "/orders/:orderid",
views: {
'menuContent': {
templateUrl: "app/views/orderdetail.html",
controller: 'OrderDetailCtrl'
}
}
})
.state('app.loyaltyhistory', {
url: "/loyaltyhistory",
cache: false,
views: {
'menuContent': {
templateUrl: "app/views/loyaltyhistory.html",
controller: 'LoyaltyHistoryCtrl'
}
}
})
.state('app.notifications', {
url: "/notifications",
cache: false,
views: {
'menuContent': {
templateUrl: "app/views/notifications.html",
controller: 'NotificationsCtrl'
}
}
});
$urlRouterProvider.otherwise('/app/products');
});
var serviceUrl = 'http://localhost:6787/';
app.constant('ngAuthSettings', {
apiServiceBaseUri: serviceUrl,
clientId: 'ngAuthApp',
loginCredentail: 'loginCredentail'
});
Here is my Service
app.factory('loyaltyservice', ['$http', '$q', '$log', 'ngAuthSettings', function ($http, $q, $log, ngAuthSettings) {
var loyaltyFactory = {};
var webAPIbase = ngAuthSettings.apiServiceBaseUri;
var loginCredentailKey = ngAuthSettings.loginCredentail;
var getLoyaltyTransactionDetails = function (userId) {
var deferred = $q.defer();
$http({
method: 'GET',
url: webAPIbase + "api/Loyalty/GetLoyaltyTransactionDetails",
params: {
userId: userId
}
}).success(function (response) {
deferred.resolve(response);
}).error(function (err, status, header, config) {
deferred.reject(err);
});
return deferred.promise;
};
loyaltyFactory.getLoyaltyTransactionDetails = getLoyaltyTransactionDetails;
return loyaltyFactory;
}]);
Any Help really appreciate.
Sorry Guys. I forgot to enable to port in firewall. After enabaling it is started to work.
part of myApp.js:
.state('app.home', {
url: "/home",
views: {
'menuContent': {
templateUrl: "templates/home.html"
}
}
})
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl',
resolve : {
myCurrentUser : function(myCurrentUserServ) {
return myCurrentUserServ.promiseToHaveMyCurrentUser();
}
},
})
.state('app.list', {
url: "/lists/:listId",
views: {
'menuContent': {
templateUrl: "templates/listDashboard.html",
controller: 'listDashboardCtrl',
resolve : {
currentList : function(currentListServ, $stateParams) {
return currentListServ.promiseToHaveList($stateParams.listId);
}
},
}
}
})
.state('app.createWordsList', {
url: "/create-list",
views: {
'menuContent': {
templateUrl: "templates/createWordsList.html",
controller: 'createWordsListCtrl'
}
}
});
'createWordsListCtrl' controller :
.controller('createWordsListCtrl', function($scope,myCurrentUserServ , $ionicModal, $timeout,$firebaseAuth,$state,$q) {
console.log("gg");
});
when I goes to app.createWordsList at the first time, the createWordsListCtrl is running , but if I change state (for example to 'app.home') and then return back, the createWordsListCtrl not run at all.
it's happen to all states besides those with state params(aor example app.list).
I want to access inventory by id, using link /inventory/description/:{{id}} But it isnt working, nothing shows up. how can i access it by id ?
app.config(function config( $stateProvider, $urlRouterProvider) {
$stateProvider.state('inventory',{
url:'/inventory',
views: {
"main": {
controller: 'InventoryCtrl',
templateUrl: 'inventory/main.tpl.html'
}
},
data:{ pageTitle: 'Inventory' }
}
).state('inventory.detailview',{
url:'/inventory/detailview',
views: {
"detailview": {
controller: 'InventoryCtrl',
templateUrl: 'inventory/detail.tpl.html'
}
},
data:{ pageTitle: 'DetailView' }
}
).state('inventory.description',{
url:'/inventory/description/:{{id}}',
views: {
"descriptionview": {
templateUrl: 'inventory/description.tpl.html',
controller: function($scope, Inventory){
$scope.id = Inventory.query('id');
}}
},
data:{ pageTitle: 'DescriptionView'}
});
});
my factory
app.factory('Inventory', function($resource, $http) {
return $resource('http://web.lv/api/v1/inventory/:id', {id: "#id"},
{
update: {
method: 'POST',
params: {id: '#id'},
isArray: false
},
save: {
method: 'PUT'
},
query: {
method: 'GET',
params: {id: '#id'},
isArray: false
},
create: {
method: 'POST'
},
drop: {
method: 'DELETE',
params: {id: "#id"}
}
}
);
});
my controller
app.controller('InventoryCtrl', function($scope, $http, Inventory, $location) {
//getting the objects from Inventory
$scope.info = Inventory.query();
//
$scope.id = Inventory.query('id');
}
If you are using ui-router, you can use stateParams
app.controller('InventoryCtrl', function($scope,$stateParams,Inventory) {
$scope.id = $stateParams.id;
}