$scope.ons.navigator.pushPage not work in init method - angularjs

I am following init function in app.js
$scope.init = function ()
{
if(localStorage.getItem("id")!=null && localStorage.getItem("pass")!=null)
{
alert(localStorage.getItem("id")+" "+localStorage.getItem("pass"));
var id=localStorage.getItem("id");
var pass=localStorage.getItem("pass");
$http({method: 'GET', url: site+'/login-web.php?txt_email='+id+'&txt_password='+pass}).
success(function(data, status, headers, config)
{
if(data=='error')
navigator.notification.alert("Wrong username or password.",null,"Attention.!","Try Again.!");
else
{
localStorage.setItem("id", id);
localStorage.setItem("pass", password);
alert("fire");
$scope.ons.navigator.pushPage('dashboard.html',{title : 'title'});
}
}).
error(function(data, status, headers, config)
{
alert("Please check Mobile Data.");
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
},
and i am fire init from
<body ng-controller="AppController" ng-init="init()">
I want to like this if i am login first time then i need to login and i store id and pass in localstorage and every time when application is load and init method is fire and i check id and pass from localstorage and fire server method to check id and pass if its right login is done automatically.
I am using phonegap + onsenui + angular js.
Problem is from init method
$scope.ons.navigator.pushPage('dashboard.html',{title : 'title'});
is not redirect to dashborad.

There is nothing wrong with $scope.ons.navigator.pushPage('dashboard.html',{title : 'title'});. But I think inside your <body> tag, there is no <ons-navigator> tag which is needed in order to use that function. Moreover, you need to call the function inside a setTimeout otherwise it will be called before the DOM element finishes rendering. Do as follows:
Here is what you need to add to ur controller:
app.factory('DataService', function($http) {
var service = {
requestData: function(url) {
return $http.get(url).then(function(data, status, headers, config) {
service.myData = data;
return service.myData;
});
},
myData: null,
return service;
});
app.controller('AppController', function($scope, DataService)){
$scope.init = function(){ setTimeout($scope.init_wait, 10); };
$scope.init_wait = function () {
if(localStorage.getItem("id")!=null && localStorage.getItem("pass")!=null){
alert(localStorage.getItem("id")+" "+localStorage.getItem("pass"));
var id=localStorage.getItem("id");
var pass=localStorage.getItem("pass");
var url = ite+'/login-web.php?txt_email='+id+'&txt_password='+pass;
DataService.requestData(url).then(function(data, status, headers, config) {
if(data=='error')
navigator.notification.alert("Wrong username or password.",null,"Attention.!","Try Again.!");
else {
localStorage.setItem("id", id);
localStorage.setItem("pass", password);
alert("fire");
$scope.ons.navigator.pushPage('dashboard.html',{title : 'title'});
}
});
}
}
};
Here inside your HTML
<body ng-controller="AppController" ng-init="init()">
<ons-navigator>
<!--Your HTML-->
</ons-navigator>
</body>

Related

How to update my angular scope **Updated**

I am using a service with an async call.
The service looks like that;
var routesApp = angular.module('routesApp', []);
routesApp.factory('angRoutes', function($http) {
var angRoutes = {
async: function(id) {
var data = $.param({
query: id
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
var promise = $http.post('../ajax-php.php', data, config)
.success(function (data, status, headers, config) {
return data;
console.log(data);
})
.error(function (data, status, header, config) {
});
return promise;
}
};
return angRoutes;
});
When the page first load I use one controller to fill the scope;
routesApp.controller('topRoutesCtrl', function topRoutesCtrl($scope,$http, angRoutes) {
angRoutes.async('top').then(function(data) {
$scope.angRoutes = data;
console.log(data);
});
});
This is all working great. But then I use another controller for when the user click on something.
routesApp.controller('navRoutesCtrl', function navRoutesCtrl($scope,$http, angRoutes) {
$scope.update = function(id) {
angRoutes.async(id).then(function(data) {
$scope.angRoutes = data;
console.log(data);
});
}
I am able to see the data I am getting in the console and the id does get passed in the update function and the data is corect but it seams that my scope is not getting updated. it remains the value that was first sent when the page load.
How do I update my scope?
UPDATE
as seen here
In my angular HTML I do a ng-repeat like this
<div ng-controller="topRoutesCtrl" class="ajax">
<div id="ajaxLoader"> <img class="loadingGif" src =" /images/ajax-loader.gif"> </div>
<div data-ng-repeat="r in angRoutes.data" class="routes-block" >
{{r.name}}
</div>
</div>
Now in my angular JS if I do
routesApp.controller('topRoutesCtrl', function topRoutesCtrl($scope,$http, angRoutes) {
angRoutes.async('top').then(function(data) {
$scope.angRoutes = data;
console.log(angRoutes);
});
});
Note that in the console I can see the same thing if I console.log(data) or console.log(angRoutes) My app however will only work if I do $scope.angRoutes = data; and nothing gets displayed if I do $scope.angRoutes = angRoutes;
So maybe I am using the referencve the wrong way in my ng-repeat
you can use wrapper $timeout for manual start $digest cicle
$scope.update = function(id) {
angRoutes.async(id).then(function(data) {
$timeout(function() {
$scope.angRoutes = data;
}
console.log(data);
});
}
but keep in mind that $digest cicle are triggerd automaticly after $http calls and written behavior is strange

Add Delay in angularjs

I want to add some delay in angularjs. So that it can fetch data from api. Because my api is heavy. I am calling this function. Basically i want some delay to load page so that my api work properly. I tried some time my data pull immediate some time i am getting error. When i refresh my page it work fine.
Help to put $timeout function in this angularjs
// Geting test stuff
$scope.teststuff = function () {
$scope.loading = true;
$http.get(settings.WebApiBaseUrl + 'Api/testing')
.success(function (data) {
$scope.mydata = data;
$scope.loading = false;
}).error(function (data, status, headers, config) {
alert("Error " + status )
$scope.loading = false;
})
}
Updated:
This problem can easily be solved by using resolve property of $routerProvider. Please use this config. So here the route /ed will not load until the resolve is completed, meaning the http request must return a value, only after that the page will load.
app.config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {
var settings.WebApiBaseUrl = "some url you want to use";
$routeProvider.when("/al", { templateUrl: "Views/test.html", controller: "testCtrl" })
.when("/ed", {
templateUrl: "Views/test2.html",
controller: "test2Ctrl",
resolve: {
initialize: function($http, $sessionStorage){
$http.get('api/ApiKey/' + $sessionStorage.user)
.success(function (myKey) {
return $http.get(settings.WebApiBaseUrl + 'Api/test1', { headers: { 'X-ApiKey': myKey } })
.success(function (data) {
return data;
}).error(function (data, status, headers, config) {
alert("error" + status);
});
}).error(function (data, status, headers, config) {
alert("error" + status);
});
}
}
})
.otherwise({
redirectTo: '/al'
});
}]);
Now in the controller you need to do.
app.controller( 'test2Ctrl', function ( $scope, initialize ) {
$scope.loading=false;
$scope.test1=initialize;
$scope.loading=true;
});
Old Answer:
so you have a http request which is a promise and will wait until the data is received and from your example I can see you are implementing a loading screen kind of thing until the http request is completed.
To ensure the bulky http request doesn't time out you can use.
angular.module('MyApp', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.timeout = 5000;
}]);
While the page waits for the http request to complete you can use the scope variable($scope.loading = true;) to activate a loading spinner library to mask your page. Checkout angular loading overlay or some other code to do this.
Reference:
http timeout

read parameter from current url in angular js and jsp

Hi friends, I want to read parameter from current URL of the page in
angularJS. My page URL is
'http://localhost:9999/ADMIN_APP_0.1/Security_Question.jsp?user_id=1'.I
want to read this user_id in Security_Question.jsp
I googled and I got something Route in angular but my code style and its style is quite different.And I don't know about route.
Forgot password is jsp page which is calling security question page
Forgot_Password.jsp
var app = angular.module('formSubmit', []);
app.controller('forgotController',[ '$scope', '$http', function($scope, $http) {
$scope.listOfSecurityQues=[];
$scope.getAvailableUser = function() {
var loginId= {
"user_login" :$scope.loginid
};
window.alert(" login ::::"+loginId);
var response = $http.post('loginController/loginidAvailable', loginId);
response.success(function(data, status, headers, config) {
window.location="./SecurityQuestion.jsp?user_id="+data;
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " +data+" "+status);
});
//Empty list data after process
$scope.list = [];
}; // end of getAvailableUser
Security_Question .jsp
var app = angular.module('formSubmit', []);
app.controller('forgotController', ['$scope','$http',function($scope,
$http) {
$scope.listOfUserSecurityQues = [];
$scope.getUserQuestions = function()
{
//here i want that URL user_id
var response = $http({method : 'GET',
url : "loginController/getUserQuestions"+user_id
});
response.success(function(data, status, headers, config) {
angular.forEach(data, function(value, key) {
$scope.listOfUserSecurityQues.push(value);
})
})
response.error(function(data, status, headers, config) {
})
};//end of getQuestions()
} ]);
by using $location we can read parameter of url.
app.controller('Controller', ['$scope','$http','$location',
function($scope, $http,$location)
{
$scope.Id=0;
$scope.getUserQuestions=function(){
var url = $location.search();
angular.forEach(url,function(value,key){
$scope.Id=parseInt(value);
window.alert($scope.Id);
}) }

How to provide delay in ng-controller

As soon as Html page gets loaded, it calls SuperCategoryController, where i am assigning supercategories to $scope variable.
$scope.SuperCategories = SuperCategoryService.GetSuperCategories();
But as this controller is depends on service, which in turn calls the http request. so at the time pf assignment http request is not completed. so $scope.SuperCategories is getting assiged to undefined.
sampleApp.service('SuperCategoryService', ['$http', function ($http){
var URL = 'http://localhost/cgi-bin/superCategory.pl';
var SuperCategories;
$http({
method: 'POST',
url: URL,
data: "action=GET",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).
success(function (data) {
alert (data);
if (data != null || data != 'undefined') {
SuperCategories = data;
}
})
.error(function (error) {
alert (error.message);
//$scope.status = 'Unable to retrieve super categories' + error.message;
});
//simply returns the SuperCategories list
this.GetSuperCategories = function () {
//alert (SuperCategories);
return SuperCategories;
}
}]);
sampleApp.controller('SuperCategoryController', ['$scope', 'SuperCategoryService', function ($scope, SuperCategoryService){
$scope.SuperCategories = SuperCategoryService.GetSuperCategories();
$scope.LoadSuperCategoryMapping = function()
{
alert ($scope.SelectedSuperCategory.id);
}
}]);
How to solve this problem in proper way.
I haven't tried this code myself but I would approach a solution using factory and a promise to make sure the data has been loaded. Something along these lines:
sampleApp.factory('SuperCategoryService', ['$http', function ($http){
return {
GetSuperCategories: function () {
var URL = 'http://localhost/cgi-bin/superCategory.pl';
return $http.get(URL);
}
}
}]);
sampleApp.controller('SuperCategoryController', ['$scope', 'SuperCategoryService', function ($scope, SuperCategoryService){
$scope.SuperCategories = function() {
SuperCategoryService.GetSuperCategories()
.then(function(d) {
if (d.data != undefined) {
// Your data should be loaded here
console.log(d.data);
$scope.SuperCategories = d.data;
}
})
.error(function(data, status) {
// Errors here
});
}
}]);

Where in angular should I put this code?

I have an http-method that gets some data from a google spreadsheet. I want to add this to the $scope so I can output it in the DOM. Later I might make a timed loop of this so that the $scope get's updated every 5 seconds or so.
I currently run the code in app.run:
angular.module('spreadsheet2angular', []).
run(function($http){
$http({method: 'GET', url: 'http://cors.io/spreadsheets.google.com/feeds/cells/0Aq_23rNPzvODdFlBOFRYWlQwUFBtcXlGamhQeU9Canc/od6/public/values?alt=json'}).
success(function(data, status, headers, config) {
var entries = data.feed.entry;
var phraces = [];
entries.forEach(function(entry){
var cell = entry.gs$cell;
if(!phraces[cell.row]){
phraces[cell.row] = {};
}
if(cell.col == 1)
{
phraces[cell.row].name = cell.$t;
}
else if(cell.col == 2)
{
phraces[cell.row].value = cell.$t;
}
});
phraces.forEach(function(phrace){
console.log(phrace);
});
}).
error(function(data, status, headers, config) {
console.log('error');
});
});
I'm new to angular, is this the best place to run it? I would like to run it as something that is easily reusable in different projects.
I think from what you've explained, a service would be perfect. Build it out then inject it in your controller. You can then call/use that service object whenever you would like.
I would use service/factory that returns promise. So we call async service method, get back promise and parse response into controller.
If you think to use the same call in the future, you can write generic method.
By the same way, if you are going to parse response by the same way in the future, the part of logic I would put into the service as well and wrap with $q . So the response still will be promise.
And this is an example I use that might help you to understand what I'm meaning:
app.service('apiService', ['$http', '$q', '$rootScope',
function($http, $q, $rootScope) {
var request = function(method, data) {
var deferred = $q.defer();
var configHttp = {
method: 'POST',
url: config.api + '/' + method
};
if (data !== undefined) {
configHttp.data = data;
}
$http(configHttp).success(function(data, status, headers) {
if (data.error === undefined) {
deferred.resolve(data);
} else {
deferred.reject(data);
}
}).error(function(data, status, headers) {
deferred.reject(data);
});
return deferred.promise;
}
return {
getItem: function() {
return request('get_item');
},
getItemByParams: function(id) {
return request('get_item_by_params', {id: id});
}
};
}
]);

Resources