I am new to angularjs so this is probably simple. I have this as my main app entry point:
<div ng-app="mainApp">
<div ng-view></div>
</div>
Routed as such:
$routeProvider
.when('/general', { templateUrl: '/Rewards/SelfService_General', controller: 'GeneralController' })
.when('/resources', { templateUrl: '/Rewards/SelfService_Resources', controller: 'ResourcesController' })
.otherwise({ redirectTo: '/general' });
My resources controller is as such:
appRoot.controller('ResourcesController', ['$scope', '$interval', '$http', function ($scope, $interval, $http) {
$scope.GetResources = function GetResources() {
var requestData = {
AccessKey: "",
Culture: ""
};
$http.post('http://myapi.com/etc', requestData)
.success(function (data, status, headers, config) {
$scope.ViewName = status;
alert('success');
})
.error(function (data, status, headers, config) {
$scope.ViewName = status;
alert('error');
});
};
$interval($scope.GetResources(), 5000);
}]);
On loading the page, the GetResources function is immediately called and as expected, hits the error function returning a 401 status. What surprises me is that no further calls to GetResources are made. Why is the interval ended?
Adding this answer to close the issue.
In your markup attribute name should be ng-click not ngclick.
$interval($scope.GetResources(), 5000); should be $interval($scope.GetResources, 5000);
Related
Here i'm working on a login app using AngularJS. After authentication, when I try to redirect to home page using $location, first the url will change to '/home' but suddenly the path change and shows '/undefined'. Following is my code:
var app = angular.module('app', ['ngRoute', 'ngCookies']);
var currentURL = location.protocol+'//'+location.hostname+':'+location.port;
app.constant("customConstants", {"value": "false","url": currentURL});
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'usrlib/html/login.html',
controller : 'loginController'
})
.when('/login', {
templateUrl : 'usrlib/html/login.html',
controller : 'loginController'
})
.when('/home', {
templateUrl : 'usrlib/html/home.html',
controller : 'homeController'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('loginController', function($rootScope, $scope, $http, $route, $location, customConstants) {
console.log("Inside loginController");
$scope.authenticate = function () {
var userdetails = {};
userdetails["username"]=angular.element('#username').val();
userdetails["password"]=angular.element('#password').val();
var config_json = {
headers : {
'Content-Type': 'application/json'
}
}
$http.post(customConstants.url+"/login",userdetails, config_json)
.then(function successCallback(response) {
console.log(JSON.stringify(response.data, null, "\t"));
var resp = response.data;
if(resp=="success"){
alert("Success login")
$location.path('/home');
}
else{
console.log("Login Failed");
}
}, function errorCallback(response) {
console.log(response.error);
});
};
});
app.controller('homeController', function(customConstants, $scope, $http) {
alert("Inside homeController");
$http.get(customConstants.url+"/home")
.then(function successCallback(response) {
console.log("overall_info :: "+JSON.stringify(response.data, "\t"));
}, function errorCallback(response) {
});
});
In browser it shows:
Can't find the issue, please help out.
You do not need.
$location.path('/home'); // Wrong
Try
$location.path('home'); // ryt
Just try to remove the $location Parameter from your function definition. because unless you invoke the function there is a chance of showing undefined,,
My code:
/**
* Created by maki1234 on 14.03.16.
*/
angular.module('admin', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/all.html',
controller: 'mainController'
})
.when('/details/:id', {
templateUrl: 'views/details.html',
controller: 'detailsController',
resolve: {
id: function ($route, $q) {
var q = $q.defer();
var id = parseInt($route.current.params.id, 10);
if (!isNaN(id)) {
q.resolve(id);
} else {
q.reject('Param Id must be a number!');
}
return q.promise;
}
}
})
.otherwise({
redirectTo: '/'
});
})
.controller('mainController', function () {
})
.controller('detailsController', function ($scope, $location, id, $log) {
$scope.$on('$routeChangeError', function (event, current, previous, rejection) {
$scope.error = rejection;
});
$log.info($scope.error);
});
My problem is: This code works but when ID is numeric, but when it's a string controller doesn't log anything in console. Any suggestion? (when id is numeric in console i see undefined - it's good i think)
Updated:
app.js
angular.module('admin', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/all.html',
})
.when('/details/:id', {
templateUrl: 'views/details.html',
controller: 'detailsController',
resolve: {
'id': function ($route, $q) {
var q = $q.defer();
var id = parseInt($route.current.params.id, 10);
if (!isNaN(id)) {
q.resolve(id);
} else {
q.reject('Param id must be a number!');
}
return q.promise;
}
}
})
.otherwise({
redirectTo: '/'
});
})
.controller('mainController', function ($rootScope, $location) {
$rootScope.$on('$routeChangeError', function (event, current, previous, rejection) {
$rootScope.error = rejection;
});
})
.controller('detailsController', function ($scope, id) {
$scope.id = id;
});
index.html
<div class="container-fluid">
<div class="row">
<div class="col xs-10 col-xs-offset-1" ng-controller="mainController" ng-view>
</div>
</div>
</div>
details.html
<h3>{{id}}</h3>
<h3>{{error}}</h3>
The problem is when I have valid url id is printed on the screen, but when I change id to bad value on the screen I see printed id and the error (it seems that $scope.id is saved and it's all time in memory). Second problem is when I have for example bad url I see error on the screen but when I press F5 and the page "reload" route doesn't change so i see white screen without any error (because route is the same and routeChangeError event isn't fired...).
I triggered the %a{"ng-click"=>"get_destinations(city)"}
However, it should redirect me to "destinations" controller, but it didn't
and there is no error in webconsole, what's going on ?
welcome.js.erb
var App = angular.module('App', ['ngRoute']);
App.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/depart_from/:id',
{
templateUrl: "<%= asset_path('promotion_destinations.html') %> ",
controller: 'destinations'
}
)
.otherwise({ redirectTo: '/depart_from/:id' });
}]);
App.controller("departure_cities", function($scope, $location, $http) {
$http.get("/promotion.json")
.success(function (response) {
$scope.departure_cities = response;
});
$scope.get_destinations = function(id) {
return $location.url("/depart_from/" + id);
};
});
App.controller("destinations", function($scope, $location, $http) {
$http.get("/another_city.json")
.success(function (response) {
$scope.destinations = response;
});
});
Your default controller is destinations in the $scope of destinations controller no any method like get_destinations .
Put your method in side destinations controller it will work if every thing is fine.
Well if you can link the html generated (the one that see the browser, not the server template) that would help.
However i still see an error for me in the HTML (or it's a naming problem)
get_destinations(city)
And in the javascript :
$scope.get_destinations = function(id)
Maybe you wanted to do this ?
get_destinations(city.id)
I want to redirect after login to /dashboard
$scope.submit = function (user) {
if ($scope.loginForm.$valid) {
UserService.login(user).then(
function (result) {
$location.path('/dashboard');
}, function (reason) {
$scope.msg = "username or password is not correct";
});
$scope.reset();
}
};
in app.js I want to create my menu dynamically and show dashboard.html
$routeProvider
.when('/dashboard', {
templateUrl: 'views/dashboard.html',
abstract:true,
resolve: {
menu: function (MenuService) {
return MenuService.getMenu();
}
},
controller: function ($scope, menu) {
$scope.menu = menu;
$scope.oneAtATime = true;
}
})
and in dashboard I use ng-view to load my template
<div class="content">
<div class="container">
<ng-view></ng-view>
</div>
but it catch "Maximum call stack size exceeded" error.
THE MenuService servie return promise
factory('MenuService', function ($q, $http) {
var getMenu = function () {
var deferred = $q.defer();
$http.post('/menu', 1).
success(function (data) {
deferred.resolve(data);
}).
error(function (data, status) {
deferred.reject(status);
});
return deferred.promise;
};
return{
getMenu: getMenu
}
})
I changed the MenuService.getMenu() to this:
$routeProvider
.when('/dashboard', {
templateUrl: 'views/dashboard.html',
abstract:true,
resolve: {
menu: function (MenuService) {
MenuService.getMenu().then(function(result){
return result;
});
}
},
controller: function ($scope, menu) {
$scope.menu = menu;
$scope.oneAtATime = true;
}
})
and now dashboard is loaded but without menu. then method is called after dashboard.html loading!!!!
when I remove ng-view every thing work perfectly.
What is my problem?
thank you
Basically you need to do change in your custom resolve service code. Currently your controller promise has receiving chain promise, so you should return a promise instead of return chain promise.
Code
$routeProvider
.when('/dashboard', {
templateUrl: 'views/dashboard.html',
abstract:true,
resolve: {
menu: function (MenuService) {
return MenuService.getMenu();
}
},
controller: function ($scope, menu) {
menu.then(function(data){
$scope.menu = data;
});
$scope.oneAtATime = true;
}
})
I'm developing a mobile app with Cordova and Angular JS. My app is on an easyphp localhost.
I use Angular Routes with a ng view directive in my index.html. And I've got this :
TypeError: Cannot read property 'get' of undefined
angular.module('app.controllers', [])
.controller('MainCtrl', ['$scope', function ($scope) {
$scope.status = "Accueil";
}])
.controller('ViewCtrl', ['$scope', function ($scope, $http) {
$http.get('mobile.php/getAnnonces/limit=10')
.success(function(data, status, headers, config) {
$scope.posts = data;
})
.error(function(data, status, headers, config) {
// log error
});
}])
...
If I test the URL my script returns JSON (with json_encode). Where am I wrong ?
Thanks for your help,
Regards
try to change
angular.module('app.controllers', [])
.controller('MainCtrl', ['$scope', function ($scope) {
$scope.status = "Accueil";
}])
.controller('ViewCtrl', ['$scope','$http', function ($scope, $http) {
$http.get('mobile.php/getAnnonces/limit=10')
.success(function(data, status, headers, config) {
$scope.posts = data;
})
.error(function(data, status, headers, config) {
// log error
});
}]);
Changes:
Passing $http service to controller as string so that will resolve at runtime.