I want to change state by local-storage in my application after page refresh. How to get the state?.
HTML:
<body ng-app="sampleApp">
<div class="container" ng-controller="Registration" ng-init ="temp()">
<div ui-view></div>
</div>
Controller:
var sampleApp = angular.module('sampleApp',
['ui.router','angularFileUpload','ngStorage']);
sampleApp.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('settings', {
url: '/settings',
templateUrl: '/ui/step1.htm'
.state('settings/Personal_Info', {
url: '/Personal_Info',
templateUrl: '/ui/step2.htm',
//controller: 'ProfileController'
})
.state('settings/Personal_Info_1', {
url: '/Personal_Info_1',
templateUrl: '/ui/step3.htm',
//controller: 'AccountController'
})
.state('settings/P_Info_Affiliations', {
url: '/P_Info_Affiliations',
templateUrl: '/ui/step4.htm',
//controller: 'ProfileController'
});
$urlRouterProvider.otherwise('/settings');
});
sampleApp.controller("Registration",
function ($scope, $location, $http, $state, $localStorage){
$scope.currentstep = 1;
$scope.formData = {};
$scope.temp = function()
{ alert($localStorage.currentstep);
if($localStorage.currentstep > 0) {
$scope.currentstep = $localStorage.currentstep;
$scope.getStepUrl();
}
}
$scope.next = function(formData){
console.log($scope.currentstep);
//console.log($scope.formData);
if (formData.check == 1) {
$scope.currentstep = $scope.currentstep + 1;
$localStorage.currentstep = $scope.currentstep;
alert("Everything is validated. We can go ahead");
$http({
method : 'POST',
url : 'addstep?step'+ $scope.currentstep,
data : $scope.formData,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
$scope.errorName = data.errors.name;
$scope.errorUserName = data.errors.username;
$scope.errorEmail = data.errors.email;
} else {
$scope.message = data.message;
}
});
$scope.getStepUrl();
}
else {
alert("Some issues in input data.");
}
}
$scope.getStepUrl = function() {
if($scope.currentstep == 1){
$state.go('settings');
}
else if($scope.currentstep == 2){
$state.go('settings/Personal_Info');
alert("i am step 2");
}
else if($scope.currentstep == 3){
$state.go('settings/Personal_Info_1');
}
}
});
I am not geting state properly.
how to solve this issue?
Thank you for your help in advance.
You can get the current state via $state provider and state.current.name
So you can ask for current state in each controller or service you would like to use
Remove the default state
$urlRouterProvider.otherwise('/settings');
Use the else statment in a function
if($localStorage.currentstep > 0) {
$scope.currentstep = $localStorage.currentstep;
$scope.getStepUrl();
}else{
$state.go('settings');
}
Related
Below is app.js file contain myApp module. I am facing issue with $scope variable not updated on view file which is rendered using $state.
I am calling showArticles function on ng-change event from one of view file which got rendered using $state.go statement. This view rendered after user login. All code snap given below. Also facing same issue after AJAX success response $scope not getting updated on view file.
var myApp = angular.module('myApp', ['ui.router']);
myApp.config(function($stateProvider, $urlRouterProvider){
$stateProvider.state('settings', {
url: '/settings',
templateUrl: 'templates/setting.html',
controller: 'adminCtrl',
})
.state('profile', {
url: '/profile',
templateUrl: 'templates/profile.html',
controller: 'adminCtrl',
})
.state('account', {
url: '/account',
templateUrl: 'templates/account.html',
controller: 'adminCtrl',
cache: false
})
.state('articleList', {
url: '/articles',
controller: 'adminCtrl',
cache: false,
templateUrl: 'templates/articleList.html',
})
.state('addArticle', {
url:'/addArticle',
templateUrl : 'templates/addArticle',
controller: 'adminCtrl',
cache: false
})
$urlRouterProvider.otherwise('/settings');
});
myApp.run(function($rootScope, $state, $location, AuthenticationService){
//array of route that dont need authentication
var routeThatDontNeedAuth = ['/settings'];
var routeClean = function(route)
{
//alert(route); alert();
if(routeThatDontNeedAuth.indexOf(route) !== -1){ alert('aaa');
return false;
}
else{
return true;
}
}
$rootScope.$on('$stateChangeStart', function(event, next, current){
if(routeThatDontNeedAuth.indexOf($location.url()) < 0)
{
if(!AuthenticationService.isLoggedIn()){
//$state.go('settings');
//alert('not logged in and page is not login page');
}
}
});
});
myApp.factory('AuthenticationService', ['$http', '$state', function($http, $state){
return{
isLoggedIn: function(){ alert('Aut ser called');
$http({
url: 'http://127.0.0.1:8081/cUlI',
method: 'GET'
}).then(function(response){
alert('testtt');console.log(response);
if(!response.data.loggedIn)
{
$state.go('settings');
}
})
}
};
}]);
myApp.controller('adminCtrl', ['$scope', '$http', '$state', 'getArticleData', function($scope, $http, $state, getArticleData){
$scope.addArticle = function(){
$state.go('addArticle');
}
// get website list
$scope.showArticles = function(){
/*$scope.articleList = 'this is default article scope value';
alert($scope.articleList)
$scope.$applyAsync(function() {
$scope.articleList = "Another value rest"; alert($scope.articleList)
});*/
$http({
method: "GET",
url: "http://127.0.0.1:8081/articleList",
params: {
website:$scope.website
}
}).then(function(responseData){
if(responseData.data.status == 'success')
{
console.log('test dataaa');
console.log(responseData);
alert('page should modified')
alert('This is test');
$scope.articleList = {id:'test', name: 'article list'};//responseData.data.data;
$scope.artLs = "I am testt model";
$state.go('articleList', 'cache: false');
}
})
}
$scope.adminLogin = function(){
var uname = $scope.username;
var pass = $scope.password ;
alert(uname+'--'+pass);
$http({
method : "GET",
url : "http://127.0.0.1:8081/adminLogin",
params: {
username : uname,
pwd: pass
}
}).then(function(response) {
console.log('succes',response);
if(response.data.status == 'success')
{
$http({
method: "GET",
url: "http://127.0.0.1:8081/webSiteList"
}).then(function(responseData){
if(responseData.data.status == 'success')
{
$scope.sara = 'testsara';
$scope.websiteData = {id : 'a', name: 'test'}; // responseData.data.data;
console.log('scope website data', $scope.websiteData);
$state.go('account', 'cache: false');
}
});
}
else
{
}
}, function(response) {
console.log('error',response)
});
}
}]);
showArticles functions get called on ng-change event from account view:
<div id="main-container" class="col-md-12 container" >
<div class="col-md-1"></div>
<div class="col-md-10">
<div class="main-body">
<div class="content">
<div class="col-md-2"></div>
<div class="col-md-8">
<h2 class="text-center">Article Listing page modified</h2>
<div class="vt-add-article">
<button type="button" ="btn btn-default text-center" ng-click="addArticle();">Add</button>
</div>
<div class="vt-article-list">
{{articleList}}
<br>
{{artLs}} -- exp value
</div>
</div>
<div class="col-md-2"></div>
</div>
</div>
</div>
<div class="col-md-1"></div>
</div>
Main Index .html file :
<html>
<head>
<meta charset="utf-8">
<title>Welcome to Vidarbha Tigers Content Panel</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="/angularp/router/css/admin.css" />
<script src="/angularp/router/js/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="/angularp/router/js/app.js"></script>
</head>
<body ng-app="myApp" ng-controller="adminCtrl">
<header>
<div class="col-md-12">
<div class="col-md-1"></div>
<div class="vt-header-content col-md-10">
<div class="vt-header-logo">
<!--<img src="/images/logo.jpg" class="img-rounded" alt="Vidarbha Tiger"> -->
</div>
<div class="vt-header-tag"><h2><!--Vidarbha Tigers--></h2></div>
</div>
<div class="col-md-1"></div>
</div>
<hr/>
</header>
<div ui-view></div>
</body>
</body>
</html>
Kindly let me know if I am missing anything in my code. I am new to angular js and facing few issues which are unknown to me
ok, I understand your issue. Your $scope variable is getting reset everytime you call a view. Hence, you dont see any value. You will have to save the value and then retrieve it when your view gets loaded. I have updated your code below, try and let me know if it works or not
SOLUTION 1:
Create one more factory:
myApp.factory('persistService', ['$rootScope', function($rootScope){
var articleList = '';
return{
saveArticleList: function(data) {
articleList = data;
},
getArticleList: function() {
return articleList;
}
};
}]);
Then in your controller include the above service and save the articleList and when you go to your new view, intialize your articleList using the 'persistService' as below :
myApp.controller('adminCtrl', ['$scope', '$http', '$state', 'persistService', 'getArticleData', function($scope, $http, $state, getArticleData, persistService){
//Initialize your articleList
$scope.articleList = persistService.getArticleList();
$scope.addArticle = function(){
$state.go('addArticle');
}
// get website list
$scope.showArticles = function(){
/*$scope.articleList = 'this is default article scope value';
alert($scope.articleList)
$scope.$applyAsync(function() {
$scope.articleList = "Another value rest"; alert($scope.articleList)
});*/
$http({
method: "GET",
url: "http://127.0.0.1:8081/articleList",
params: {
website:$scope.website
}
}).then(function(responseData){
if(responseData.data.status == 'success')
{
console.log('test dataaa');
console.log(responseData);
alert('page should modified')
alert('This is test');
//Save your data
persistService.setArticleList('This is a test');
//$scope.articleList = {id:'test', name: 'article list'};//responseData.data.data;
$scope.artLs = "I am testt model";
$state.go('articleList', 'cache: false');
}
})
}
$scope.adminLogin = function(){
var uname = $scope.username;
var pass = $scope.password ;
alert(uname+'--'+pass);
$http({
method : "GET",
url : "http://127.0.0.1:8081/adminLogin",
params: {
username : uname,
pwd: pass
}
}).then(function(response) {
console.log('succes',response);
if(response.data.status == 'success')
{
$http({
method: "GET",
url: "http://127.0.0.1:8081/webSiteList"
}).then(function(responseData){
if(responseData.data.status == 'success')
{
$scope.sara = 'testsara';
$scope.websiteData = {id : 'a', name: 'test'}; // responseData.data.data;
console.log('scope website data', $scope.websiteData);
$state.go('account', 'cache: false');
}
});
}
else
{
}
}, function(response) {
console.log('error',response)
});
}
}]);
Let me know if this helps!
EDIT::
SOLUTION 2:
There is another way you can accomplish the same just by making a change in your controller code. See below code:
myApp.controller('adminCtrl', ['$scope', '$http', '$state', 'getArticleData', function($scope, $http, $state, getArticleData){
//Initialize your articleList
$scope.articleList = $scope.articleList || {};
$scope.addArticle = function(){
$state.go('addArticle');
}
// get website list
$scope.showArticles = function(){
/*$scope.articleList = 'this is default article scope value';
alert($scope.articleList)
$scope.$applyAsync(function() {
$scope.articleList = "Another value rest"; alert($scope.articleList)
});*/
$http({
method: "GET",
url: "http://127.0.0.1:8081/articleList",
params: {
website:$scope.website
}
}).then(function(responseData){
if(responseData.data.status == 'success')
{
console.log('test dataaa');
console.log(responseData);
alert('page should modified')
alert('This is test');
//Save your data
$scope.articleList = {id:'test', name: 'article list'};//responseData.data.data;
$scope.artLs = "I am testt model";
$state.go('articleList', 'cache: false');
}
})
}
$scope.adminLogin = function(){
var uname = $scope.username;
var pass = $scope.password ;
alert(uname+'--'+pass);
$http({
method : "GET",
url : "http://127.0.0.1:8081/adminLogin",
params: {
username : uname,
pwd: pass
}
}).then(function(response) {
console.log('succes',response);
if(response.data.status == 'success')
{
$http({
method: "GET",
url: "http://127.0.0.1:8081/webSiteList"
}).then(function(responseData){
if(responseData.data.status == 'success')
{
$scope.sara = 'testsara';
$scope.websiteData = {id : 'a', name: 'test'}; // responseData.data.data;
console.log('scope website data', $scope.websiteData);
$state.go('account', 'cache: false');
}
});
}
else
{
}
}, function(response) {
console.log('error',response)
});
}
}]);
is the alert that you have put printing the correct value?
Based on my understanding I think you set the articleList on ng-change called in one view file. After that you change state and go to another view file where you expect to see the updated articleList value which you set in the previous view. But, I think what may be happening is that when you navigate to the second view your controller might be getting reloaded and your $scope.articleList gets reset. Try printing the value of articleList before and after you change view.
To prevent this you can try using angular services to save the articleList value
This is my app.js
angular.module('app', ['ui.router', 'satellizer'])
.constant('API_URL', 'http://localhost/angular/public/api/v1/')
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
$authProvider.loginUrl = 'angular/public/api/authenticate';
$urlRouterProvider.otherwise('/auth');
$stateProvider
.state('auth', {
url: '/auth',
templateUrl: 'app/view/login.html',
controller: 'AuthController as auth'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'app/view/dashboard.tmpl.html',
params: {
model: ''
}
})
.state('dashboard.employees', {
templateUrl: 'app/view/employee.tmpl.html',
controller: 'employeesController',
}).state('dashboard.test', {
templateUrl: 'app/view/edit.tmpl.html',
controller: 'employeesController',
})
});
When I click ui-sref="dashboard.employees" controller calls twice.
calls twice
This is my controller which I want to use for all views. I developed cms on laravel and angular. I can't create a new controller for every table entity.
angular.module('app')
.controller('employeesController', function($scope, $http, API_URL,$stateParams) {
//retrieve employees listing from API
$scope.employees = '';
$http.get(API_URL + $stateParams.model)
.success(function(response) {
$scope.employees = response;
});
//show modal form
$scope.toggle = function(modalstate, id) {
$scope.modalstate = modalstate;
switch (modalstate) {
case 'add':
$scope.form_title = "Add New Employee";
break;
case 'edit':
$scope.form_title = "Employee Detail";
$scope.id = id;
$http.get(API_URL + $stateParams.model+'/' + id)
.success(function(response) {
console.log(response);
$scope.employee = response;
});
break;
default:
break;
}
$('#myModal').modal('show');
}
//save new record / update existing record
$scope.save = function(modalstate, id) {
var url = API_URL + "employees";
//append employee id to the URL if the form is in edit mode
if (modalstate === 'edit') {
url += "/" + id;
}
console.log('saved');
$http({
method: 'POST',
url: url,
data: $.param($scope.employee),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(response) {
var index = _.findIndex($scope.employees, function(b) {
return b.id == $scope.employee.id;
});
console.log(index);
if (index != -1) {
$scope.employees[index] = $scope.employee;
} else {
console.log($scope.employee);
$scope.employee.id = response;
$scope.employees.push($scope.employee);
console.log($scope.employees);
}
$('#myModal').modal('toggle');
}).error(function(response) {
console.log(response);
alert('This is embarassing. An error has occured. Please check the log for details');
});
}
//delete record
$scope.confirmDelete = function(employee) {
var isConfirmDelete = confirm('Are you sure you want this record?');
if (isConfirmDelete) {
$http({
method: 'DELETE',
url: API_URL + 'employees/' + employee.id
}).
success(function(data) {
_.remove($scope.employees, function(n) {
return n.id == employee.id;
});
console.log(data);
}).
error(function(data) {
console.log(data);
alert('Unable to delete');
});
} else {
return false;
}
}
});
Where is my mistake? How can I fix that?
kindly check, if you are called the controller in your employee.tmpl.html page, like ng-controller="employeesController"
Please remove it, if you call the ng-controller in your html
I currently have code for a form submission login that works with ng-route, however i want to convert it to UI router. I currently have MVC java controller for rest services. However here is my main app with configure statements:
var reportingDashboard = angular
.module('reportingDashboard', [ 'ngRoute', 'ui.router', 'ngMdIcons', 'chart.js'])
.config(
function($routeProvider, $httpProvider, $stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(true);
/* $routeProvider.when('/', {
templateUrl : '/home/temp.html',
controller : 'home',
controllerAs : 'controller'
}).when('/login', {
templateUrl : '/home/loginCtrl/login.html',
controller : 'navigation',
controllerAs : 'controller'
}).otherwise("/")
*/
$urlRouterProvider.otherwise('/');
$stateProvider
.state('login',{
url:'/login',
templateUrl : '/home/loginCtrl/login.html',
controller : 'navigation',
controllerAs : 'controller'
})
.state('home',{
url:'/',
templateUrl : '/home/temp.html',
controller : 'home',
controllerAs : 'controller'
})
.state('home.index', {
views:{
'': {
templateUrl:"/home/reportingTemp/repoHtml.html"
},
'reportingGraph':{
templateUrl:'/home/reportingTemp/repoGraph.html',
controller: 'reportingGraphCtrl'
}
}
})
.state('home.admin', {
views:{
'': {
templateUrl:"/home/adminTemp/adminHtml.html"
},
'adminGraph':{
templateUrl:'/home/adminTemp/adminReport.html',
controller:'adminCtrl'
}
}
})
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
}).run(function(auth) {
// Initialize auth module with the home page and login/logout path
// respectively
console.log("is the auth function being called?")
auth.init('/', '/login', '/logout');
});
From this I have the auth factory:
reportingDashboard.factory(
'auth',
function($rootScope, $http, $location) {
enter = function() {
if ($location.path() != auth.loginPath) {
console.log($location.path());
auth.path = $location.path();
if (!auth.authenticated) {
$location.path(auth.loginPath);
}
}
}
var auth = {
authenticated : false,
loginPath : '/login',
logoutPath : '/logout',
homePath : '/',
path : $location.path(),
authenticate : function(credentials, callback) {
var headers = credentials && credentials.username ? {
authorization : "Basic "
+ btoa(credentials.username + ":"
+ credentials.password)
} : {};
$http.get('user', {
headers : headers
}).success(function(data) {
if (data.name) {
auth.authenticated = true;
} else {
auth.authenticated = false;
console.log("The use isnt logged in")
}
callback && callback(auth.authenticated);
$location.path(auth.path==auth.loginPath ? auth.homePath : auth.path);
}).error(function() {
auth.authenticated = false;
callback && callback(false);
});
},
clear : function() {
$location.path(auth.loginPath);
auth.authenticated = false;
$http.post(auth.logoutPath, {}).success(function() {
console.log("Logout succeeded");
}).error(function(data) {
console.log("Logout failed");
});
},
init : function(homePath, loginPath, logoutPath) {
auth.homePath = homePath;
auth.loginPath = loginPath;
auth.logoutPath = logoutPath;
auth.authenticate({}, function(authenticated) {
if (authenticated) {
$location.path(auth.path);
}
})
// Guard route changes and switch to login page if unauthenticated
$rootScope.$on('$routeChangeStart', function() {
enter();
});
}
};
return auth;
});
From this I have the navigation controller:
reportingDashboard.controller(
'navigation',
function($route, auth, $location) {
var self = this;
self.credentials = {};
self.tab = function(route) {
return $route.current && route === $route.current.controller;
};
self.authenticated = function() {
return auth.authenticated;
}
self.login = function() {
auth.authenticate(self.credentials, function(authenticated) {
if (authenticated) {
console.log("Login succeeded")
self.error = false;
} else {
console.log("Login failed")
self.error = true;
}
})
};
self.logout = auth.clear;
});
Also i have the home controller as well:
reportingDashboard.controller('home', function($http) {
var self = this;
$http.get('/user/').success(function(data) {
self.user = data.name;
});
});
the console just returns a 401 and redirects me to the home page of the application. Any advice would be great Thankyou!! I can include any more info if it helps.
My suggestion: in angular.run function bind listener to $stateChangeStart event. Each time user will go to some state, you will check that user is authenficated. If he is, continue transition, else - save transition state and params, go to login page and after user will successfully logged in, you will redirect him to requested state/page. Something like this:
myApp.run(function ($rootScope, principal, $state, myStateProvider, userService) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
if (toState.name !== 'login') {
myStateProvider.setNextState(toState, toParams);
}
if (!principal.isAuthenticated()) {
event.preventDefault();
principal.checkAuthentication().then(function() {
$state.go(toState, toParams);
});
} else if (principal.isAuthenticated() && toState.name === 'login') {
event.preventDefault();
myStateProvider.redirectFromLogin();
}
});
})
I want to load two APIs before page is going to load For it i have used the following code in $stateProvider
.state('admin-panel.default.jobadd', {
url: '/jobadd/:jobID',
templateUrl: 'app/search/jobadd.tmpl.html',
controller: 'JobaddController',
resolve: {
jobAdd: ['Search', '$stateParams','$q', function(Search,$stateParams,$q) { //Search is service
var jobAdd = Search.jobAdd($stateParams.jobID);
var isApplied = Search.is_job_applied($stateParams.jobID);
jobAdd.$promise.then(function(response) {console.log('Resource 1 data loaded!')});
isApplied.$promise.then(function(response) {console.log('Resource 2 data loaded!')});
return $q.all([jobAdd.$promise, isApplied.$promise]);
}]
},
data: {
requireLogin: true
}
});
})
But it's not give the data when injects to the controller, page seems as blank
my controller code is
.controller('JobaddController', function ($scope, $mdDialog, $state, jobAdd, Profile) {
$scope.jobs = jobAdd[0];
$scope.benifits = jobAdd[0].benifits;
if($scope.jobs.short_listed == 1)
$scope.jobs.flag = true;
else
$scope.jobs.flag = false;
$scope.checkShortList= function(job){
if(job.flag){
Profile.rmShortList(job.short_list_id);
job.flag = false;
}
else{
if(job.short_list_id === null){
Profile.addNewShortList(job.id).then(function(response){
job.short_list_id = response.short_list_id;
});
}
else
Profile.addShortList(job.short_list_id,job.id);
job.flag = true;
}
};
$scope.companyModal = function(ev) {
$mdDialog.show({
controller: 'CompanyDetailsController',
templateUrl: 'app/search/company-details.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
})
.then(function(answer) {
$scope.alert = 'You said the information was "' + answer + '".';
}, function() {
$scope.alert = 'You cancelled the dialog.';
});
};
$scope.applyModal = function(ev) {
$mdDialog.show({
controller: 'ApplyController',
templateUrl: 'app/search/apply.tmpl.html',
locals: { Jobid: $scope.jobs.id },
parent: angular.element(document.body),
targetEvent: ev,
resolve: {
shortProfile: ['Profile', function(Profile) {
return Profile.shortProfile();
}]
},
})
.then(function(answer) {
$scope.alert = 'You said the information was "' + answer + '".';
}, function() {
$scope.alert = 'You cancelled the dialog.';
});
};
var container = angular.element(document.getElementById('container'));
var section2 = angular.element(document.getElementById('section-2'));
$scope.toTheTop = function() {
container.scrollTop(0, 5000);
};
$scope.toSection2 = function() {
container.scrollTo(section2, 0, 1000);
};
})
in service code
.service('Search', [ '$http', '$q', 'API',
function($http, $q, API) {
var data = '';
this.jobAdd = function(job_id) {
var def = $q.defer();
$http({
url: API.url+'get_job_add_detail?job_id=' + job_id,
method: "GET"
}).success(function(response) {
if(response.status == 'Success'){
data = response.data;
def.resolve(data);
}
}).error(function(response) {
console.log (response);
if(response.status == 'Failed'){
data = response.msg;
def.reject(data);
}
});
return def.promise;
}
this.isJobApplied = function(job_id) {
var def = $q.defer();
$http({
url: API.url+'is_job_applied?job_id='+job_id,
method: "GET",
}).success(function(response) {
if(response.status == 'Success'){
data = response.data;
def.resolve(data);
}
}).error(function(response) {
console.log (response);
if(response.status == 'Failed'){
data = response.msg;
def.reject(data);
}
});
return def.promise;
}
}]);
What's the wrong here?? how to attach more than on service in $state resolve?
simply you can for more than one service.
resolve: {
jobAdd: ['Search', '$stateParams', function(Search,$stateParams) {
return Search.jobAdd($stateParams.jobID);
}],
isApplied: ['Search', '$stateParams', function(Search,$stateParams) {
return Search.isJobApplied($stateParams.jobID);
}]
}
I've tried different variations of $apply() and $digest() to no avail.
The binding should update once the courier is no longer null with the name of the courier, however nothing is happening. I've been able to log the name of the courier when they are assigned, however the dom element is not updating. I'm using jade and compiling to html without any issues elsewhere in the application. I'm also calling the refreshDelivery function immediately prior to rendering the view shown below, which is working correctly.
app.js:
var storeController = require('./controllers/controller');
var storeApp = angular.module('AngularStore', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/store', {
templateUrl: 'views/store.html',
controller: storeController }).
when('/products/:productSku', {
templateUrl: 'views/product.html',
controller: storeController }).
when('/cart', {
templateUrl: 'views/shoppingCart.html',
controller: storeController }).
when('/delivery', {
templateUrl: 'views/delivery.html',
controller: storeController }).
otherwise({
redirectTo: '/store' });
}])
.controller('storeController', storeController);
controller.js:
function storeController($scope, $routeParams, $http, $interval, DataService) {
// get store and cart from service
$scope.store = DataService.store;
$scope.cart = DataService.cart;
$scope.mapInit = DataService.mapInit;
// use routing to pick the selected product
if ($routeParams.productSku != null) {
$scope.product = $scope.store.getProduct($routeParams.productSku);
}
// var locationOptions = {
// enableHighAccuracy: true,
// timeout: 5000,
// maximumAge: 0
// }
// navigator.geolocation.getCurrentPosition(function(pos){
// var mapOptions = {
// center: { lat: pos.coords.latitude, lng: pos.coords.longitude},
// zoom: 13
// };
// var map = new google.maps.Map(document.getElementById('map'),
// mapOptions);
// });
$scope.search = function(query){
var responseObject;
console.log('in search');
$http({
url:'/apiCall',
data: {data: '/products?keyword=' + query + '&latlong=36.125962,-115.211263'},
method: 'POST'
})
.then(function(response){
responseObject = response.data.data;
responseObject.forEach(function(data){
var productData = {
sku: data.Id.SkuPartNumber,
productName: data.Description.Name,
desc: data.Description.BrandName,
price: data.Price.DisplayPrice,
url: data.Description.ImageURL,
storeNumber: data.StoreNumber
}
var temp = new product(productData)
$scope.store.addProduct(temp)
});
});
}
$scope.getDeliveryQuote = function(){
var responseObject;
$scope.quoted = false;
var storeNumber = $scope.cart.items[0].storeNumber
console.log($scope.cart.items[0].storeNumber);
var url = '/delivery_quote?drop_off_latlong=36.125962,-115.211263&pickup_store_number='.concat(storeNumber);
$http({
url: '/apiCall/',
data: {data: url},
method: 'POST'
})
.then(function(response){
$scope.quoted = true;
console.log(response.data.id);
$scope.quote = response.data.fee;
$scope.quoteId = response.data.id
})
}
$scope.submitOrder = function(){
var url = '/submit_delivery?drop_off_latlong=36.125962,-115.211263&pickup_store_number=0001709&manifest=puppies&phone_number=555-555-5555"e_id=' + $scope.quoteId + '&customer_name=Arnold';
$http({
url: '/apiCall/',
data: {data: url},
method: 'POST'
})
.then(function(response){
console.log(response);
$scope.deliveryId = response.data.id;
$scope.refreshDelivery();
window.location.href='/#/delivery';
})
}
$scope.refreshDelivery = function() {
var url = '/update?delivery_id='.concat($scope.deliveryId);
var promise = $interval(function(){
$http({
url: '/apiCall/',
data: {data: url},
method: 'POST'
})
.then(function(resp) {
$scope.update = resp.data;
if (resp.data.courier){
$scope.update.courier = resp.data.courier;
console.log($scope.update.courier.name);//outputs correct name
$scope.$apply();
}
//stops when complete
if ($scope.update.complete){
$interval.cancel(promise);
}
})
}, 5000 );
}
}
module.exports = storeController;
Jade before compiling to HTML:
Partial:
p.text-info {{update.courier.name}} is on their way!
Default:
html(ng-app='AngularStore')
head
// includes for jquery, angular, and bootstrap
script(src="https://maps.googleapis.com/maps/api/js?sensor=false")
script(src='bower_components/jquery/dist/jquery.min.js')
script(rel='stylesheet' href='bower_components/bootstrap/dist/css/bootstrap.min.css')
script(src='bower_components/angular/angular.js')
script(src='bower_components/angular-route/angular-route.js')
// includes for the Angular Store app
script(src='/js/main.js')
script(src='/js/bundle.js')
link(href='/styles/main.css', rel='stylesheet', type='text/css')
|
body
.container-fluid
.row-fluid
.span10.offset1
h1.well
a(href='default.html')
| Angular Store
div(ng-view='')
I found a way around the $scope issue by creating a separate controller to handle updates.
app:
var storeController = require('./controllers/storeController'),
deliveryController = require('./controllers/deliveryController');
var storeApp = angular.module('AngularStore', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/store', {
templateUrl: 'views/store.html',
controller: storeController }).
when('/products/:productSku', {
templateUrl: 'views/product.html',
controller: storeController }).
when('/cart', {
templateUrl: 'views/shoppingCart.html',
controller: storeController }).
when('/delivery/:id', {
templateUrl: 'views/delivery.html',
controller: deliveryController }).
otherwise({
redirectTo: '/store' });
}])
.controller('storeController', storeController);
new deliveryController
function deliveryController($scope, $routeParams, $http, $interval) {
console.log($routeParams);
var refreshDelivery = function(id) {
var url = '/update?delivery_id='.concat(id);
var promise = $interval(function(){
$http({
url: '/apiCall/',
data: {data: url},
method: 'POST'
})
.then(function(resp) {
$scope.update = resp.data;
if (resp.data.courier){
$scope.update.courier = resp.data.courier;
console.log($scope.update.courier.name);//outputs correct name
}
//stops when complete
if ($scope.update.complete){
$interval.cancel(promise);
}
})
}, 5000 );
}
refreshDelivery($routeParams.id);
}
module.exports = deliveryController;