I have a very simple AngularJs app.
Here my app.js file:
angular.module('myApp', [
'ngRoute',
'ngResource',
'ui.bootstrap',
'ui.router',
'myApp.controllers'
]).
config(['$stateProvider', function($stateProvider) {
$stateProvider.
state('home', {
url: "/{Id:[0-9]}",
templateUrl: 'html/home.html',
controller: 'HomeCtrl'
});
}]);
And my controllers.js file:
angular.module('myApp.controllers', []).
controller('HomeCtrl', ['$stateParams', function($stateParams) {
console.log($stateParams.Id);
}]);
The return of the console.log($stateParams.Id) is undefined. While I'm expecting "1" (my Id).
Otherwise if I ask for console.log($stateParams) it returns a function (?!?):
function l(a){function c(a){var b=r({},a,{data:Dc(a.data,a.headers,d.transformResponse)});return 200<=a.status&&
300>a.status?b:m.reject(b)}var d={method:"get",transformRequest:e.transformRequest,transformResponse:e.transformResponse},f=function(a){function b(a){var c;q(a,function(b,d){Q(b)&&(c=b(),null!=c?a[d]=c:delete a[d])})}var c=e.headers,d=r({},a.headers),f,g,c=r({},c.common,c[A(a.method)]);b(c);b(d);a:for(f in c){a=A(f);for(g in d)if(A(g)===a)continue a;d[f]=c[f]}return d}(a);r(d,a);d.headers=f;d.method=Ia(d.method);(a=Mb(d.url)?b.cookies()[d.xsrfCookieName||e.xsrfCookieName]:s)&&(f[d.xsrfHeaderName||
e.xsrfHeaderName]=a);var h=[function(a){f=a.headers;var b=Dc(a.data,Cc(f),a.transformRequest);w(a.data)&&q(f,function(a,b){"content-type"===A(b)&&delete f[b]});w(a.withCredentials)&&!w(e.withCredentials)&&(a.withCredentials=e.withCredentials);return u(a,b,f).then(c,c)},s],k=m.when(d);for(q(x,function(a){(a.request||a.requestError)&&h.unshift(a.request,a.requestError);(a.response||a.responseError)&&h.push(a.response,a.responseError)});h.length;){a=h.shift();var l=h.shift(),k=k.then(a,l)}k.success=
function(a){k.then(function(b){a(b.data,b.status,b.headers,d)});return k};k.error=function(a){k.then(null,function(b){a(b.data,b.status,b.headers,d)});return k};return k}
While I'm expecting {Id: "1"}.
What am I doing wrong???
Just to try I changed my state in the following way:
$stateProvider.
state('home', {
url: "/{Id:[0-9]}",
templateUrl: 'html/home.html',
controller: function($stateParams){
console.log($stateParams);
}
});
}]);
And it works! It returns {Id: "1"} but unfortunately this is not an option for me since what I described here is a small portion of a much bigger and complicated App (so I'd like to have app.js and controllers.js files).
Any suggestion?
Related
I have a problem to use $rootScope.$on in AngularJS, I try to call alert, but unsuccess, nothing error in console, I generate this project use yeoman generator, I don't know why, this is my script, please correct my script.
'use strict';
angular
.module('siapApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'ui.router',
'ui.bootstrap'
])
.config(['$stateProvider', '$locationProvider', '$urlRouterProvider', '$qProvider',
function ($stateProvider, $locationProvider, $urlRouterProvider, $qProvider) {
$stateProvider
.state('main', {
url: '/',
views: {
'content#': {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
}
}
})
.state('about', {
url: '/about',
views: {
'content#': {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
}
}
})
$locationProvider.hashPrefix('');
$urlRouterProvider.otherwise('/');
$qProvider.errorOnUnhandledRejections(false);
}])
.run(['$rootScope', '$state', '$stateParams',
function($rootScope, $state, $stateParams) {
$rootScope.$on('$stateChangeStart', function(event, toState, toStateParams) {
alert('success'); /*cannot call alert*/
});
}
]);
Please anyone help me.
Thanks.
This should work in any case. The only thing I can suspect is you don't have ui-view directive on your index.html page.
<ui-view></ui-view>
I've been googling about this for the past hour but couldn't find an answer.
I want to change the template when there's a parameter passed in the URL.
I tried using hash to retrieve it by calling $location.hash in the controller but I can't figure out how to have the routeProvider detect it, here's my code:
'use strict';
angular.module('myApp.projects', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/projects', {
templateUrl: 'modules/projects/projects.html',
controller: 'projectsCtrl'
});
}])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/projects:project', {
// $routeProvider.when('/projects#project', { // Tried this and it didn't work as well
templateUrl: 'modules/projects/single-project.html',
controller: 'projectsCtrl'
});
}])
.controller('projectsCtrl',['$scope','portfolioService','$location',
function($scope,portfolioService,$location){
$scope.portfolio = portfolioService.portfolio;
console.info('$location.hash',$location.hash());
// $scope.currentProject = $location;
}])
i saw a lot of similar questions at SO, but those solutions not worked for me :(
About my site and app:
backend is wordpress with json api, angular app is on the mysite.lc/catalog/ page.
my controller:
var catalogControllers = angular.module('catalogControllers', []);
catalogControllers.controller('catalogCtrl', ['$scope', '$state', '$stateParams',
function ($scope, $state, $stateParams) {
$log.debug(angular.toJson($stateParams, true));
$http.get(url).success(function(data) {
console.log('data is loaded');
});
}
]);
my routing setup:
var catalogApp = angular.module('catalogApp', ['ui.router', 'ngResource', 'ngSanitize', 'catalogControllers']);
catalogApp.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '?producttype&colors&models',
controller: 'catalogCtrl',
onEnter: function() {
console.log('route entered');
}
});
$urlRouterProvider.otherwise("/");
}]);
So when i go to url like http://mysite.lc/catalog/#/?producttype=4&colors=5,7,9&models=17 console shows
{} from catalogCtrl, then
data is loaded from catalogCtrl $http.get, and only after that
route entered
If i do log it that way (at router config) controller: function($stateParams) { console.log($stateParams); } it doesn't output anything.
I would suggest resolving the $stateParams on its corresponding state on the .config section. Also,if it is your intention, you need to make your url name part of the url property and not just the stateParameters because ui-router doesn't automatically assign 'home' just because you declared it to be the home state. You can also make the parameters optional by declaring the 'params' property and setting everything to null.
var catalogApp = angular.module('catalogApp', ['ui.router','ngResource', 'ngSanitize', 'catalogControllers']);
catalogApp.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
params: {
productType: null,
colors: null,
models: null
}
url: '/home?productType&colors&models',
controller: 'catalogCtrl',
resolve: {
parameters: function($stateParams){
return $stateParams;
}
}
});
$urlRouterProvider.otherwise("/");
}]);
and to view it in the console, I would suggest using $log to preserve the sequence of it (I had this problem before using console.log) and angular.toJson to display the data;
var catalogControllers = angular.module('catalogControllers', []);
catalogControllers.controller('catalogCtrl', ['$scope', 'parameters', '$log'
function ($scope, parameters, $log) {
$log.debug(angular.toJson(parameters, true));
//the 'true' arguments makes the json 'prettyfied'
}
]);
let me know how it goes because it's a bit unorthodox for me to create the app which doesn't start from the root page.
I've found what was the problem, and it's small and easy (as usually :) ).
Actually everything worked fine, but i had some unmentioned $http.get calls in code above, and my logging was before any data has been loaded, so firstly i logged my $stateParams and only after that (after data has been loaded) my "home" state has been achieved.
So solution is to put work with $stateParams into $http.get(..).success() function.
So now my controller looks like
var catalogControllers = angular.module('catalogControllers', []);
catalogControllers.controller('catalogCtrl', ['$scope', '$state', '$stateParams',
function ($scope, $state, $stateParams) {
$http.get(url).success(function(data) {
console.log('data is loaded');
$log.debug(angular.toJson($stateParams, true));
});
}
]);
router:
var catalogApp = angular.module('catalogApp', ['ui.router', 'ngResource', 'ngSanitize', 'catalogControllers']);
catalogApp.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '?producttype&colors&models',
controller: 'catalogCtrl',
onEnter: function() {
console.log('route entered');
}
});
$urlRouterProvider.otherwise("/");
}]);
URL like http://mysite.lc/catalog/#/?producttype=4&colors=5,7,9&models=17 now outputs in console this:
data is loaded from $http.get in controller
route entered from router
{ "producttype": "4", "colors": "5,7,9", "models": "17" } from $stateParams in controller
Please add your comment, because i'm really newbie in angular and will appreciate any opinions on that.
I have a:
main module : kp
sub module : kp.venue
I want kp.venue to have it's own "route" definitions (for all paths relative to that module).
This is what I am trying to achieve in the code bellow.
Can anyone explain me why it doesn't work?
I followed the technique presented in this post: https://stackoverflow.com/a/15301427/971008
(function () {
'use strict';
angular.module('kp.venue', [])
.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when("/venue", {
template : "<p>This is the venue module</p>",
controller: "VenueCtrl"
});
}
])
.controller('VenueCtrl', ['$scope',
function($scope){
console.log("VenueController");
}
]);
angular.module('kp', ['ngRoute', 'ngAnimate', 'kp.venue'])
.config(['$locationProvider', '$routeProvider',
function($locationProvider, $routeProvider) {
$locationProvider.html5Mode({enabled:true, requireBase:false});
$routeProvider
.when("/", {
template: "<p>main app</p>",
controller: "MainController"
})
.otherwise({
redirectTo: '/'
});
}
]);
//Load controller
angular.module('kp')
.controller('MainController', ['$scope',
function($scope) {
$scope.test = "Testing...";
}
]);
}());
Note that I have already tried to move "kp.venue" bellow the definition of "kp" module to be sure that it was not a problem related to things not being loaded in the right order.
I am new with Angularjs
and I want to use angular-translate
here is the site
http://pascalprecht.github.io/angular-translate/
I refer it document , and I got the error
Uncaught TypeError: Cannot call method 'useStaticFilesLoader' of undefined from remoteApp
here is my code
app.js
angular.module('remoteApp', ['ui.bootstrap', 'ui.router', 'ngResource', 'truncate',
'pascalprecht.translate'])
.config(['$translateProvider', function ($routeProvider, $stateProvider, $urlRouterProvider,
$translateProvider) {
$translateProvider.useStaticFilesLoader({
prefix: 'languange/locale-',
suffix: '.json'
});
$translateProvider.preferredLanguage('en');
$translateProvider.useLocalStorage();
$stateProvider
.state('index', {
url: "",
views: {
"viewA": {
templateUrl: "views/main.html",
controller: 'MainCtrl'
},
"viewB": {
templateUrl: "views/appList.html",
controller: 'MainCtrl'
},
"viewC": {
templateUrl: "views/appTree.html",
controller: 'ApptreeCtrl'
}
},
})
.state('applicatoion', {
url: "/applicatoion",
views: {
"viewA": {
templateUrl: "views/main.html",
controller: 'MainCtrl'
},
"viewB": {
templateUrl: "views/appList.html",
controller: 'MainCtrl'
},
"viewC": {
templateUrl: "views/appTree.html",
controller: 'ApptreeCtrl'
}
}
})}]);
I have no idea about it ,
please help
Right now this is how you are calling .config
config(['$translateProvider', function ($routeProvider, $stateProvider, $urlRouterProvider,
$translateProvider) {
// ...
}]);
.config has its parameters ( dependencies ) injected by AngularJS, there are two ways to call config;
1 - Pass in a function and AngularJS will read the parameter names and find the matching dependencies.
2 - Pass in an array, of which the last item is a function, and the other items are names of dependencies, if you use this, AngularJS will not read the function's parameter names. The reason this exists is so you can minify your code; because minifying would change the parameter names, and AngularJS uses those names to find dependencies.
What you have now is you specify only one dependency, '$translateProvider', which means the first parameter being passed to the function is the translateProvider, and the other parameters end up being undefined, because you didn't ask for more dependencies.
What you can do is either let AngularJS read your dependency names like this
config(function ($routeProvider, $stateProvider, $urlRouterProvider, $translateProvider) {
// ...
});
Or you can specify all of the dependencies, matching the function parameter list like this, allowing you ( only if you do this consistently ) to minify your code without breaking it.
config(['$routeProvider', '$stateProvider', '$urlRouterProvider', '$translateProvider',
function ($routeProvider, $stateProvider, $urlRouterProvider, $translateProvider) {
// ...
}]);