Here is a snipper of my Angular app :
routes.js
angular.module("App")
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/users/:id', {
templateUrl : 'pages/show.html',
controller : 'UsersController',
controllerAs : 'usCtrl'
})
} ]);
my-users-controller.js
(function() {
angular.module("App")
.controller("UsersController", ['$http', '$routeParams',
function($http, $routeParams) {
alert('Hello !');
this.user= $routeParams.id;
console.log($routeParams.id);
} ]);
})();
show.html (this is inserted into ng-view)
<div class="row">
<div class="col-xs-12 col-md-4">
Hello {{ usCtrl.user }}
</div>
</div>
My controller is not invoked for some reason. When I click on my link
<a ng-href="#/users/john" ...
routing works fine , but controller is not called and usCtrl.user is not displayed. If I use inline function for controller everything works fine.
By inline I mean
...
controller : function($routeParams) {
// code
}
...
Any suggestions ?
This looks like the controller is never getting initialized and registered.
Verify that your build chain is pulling the file in correctly.
Then verify that controller registration is being invoked.
(function() {
console.log('Controller Registered');
angular.module("App")
.controller("UsersController", ['$http', '$routeParams',
function($http, $routeParams) {
alert('Hello !');
this.user= $routeParams.id;
console.log($routeParams.id);
} ]);
})();
angular.module("App",[])
.config(['$routeProvider', function($routeProvider) {
....
} ]);
Your controller getting executed immediately with module App then is get overwritten by same module App
Related
Hi This is my first angularjs app and i am facing problem in injecting controller. I have one page called index.html and described as below.
<body ng-app="RoslpApp">
<div ng-controller="RoslpAppController">
<div class="popup">
<label>Language</label>
<select ng-model="selectedItem">
<option>العربية</option>
<option>English</option>
</select>
<button ng-click="clickHandler(selectedItem)">Submit</button>
</div>
</div>
</body>
This is my js file.
var app = angular.module('RoslpApp', ['pascalprecht.translate', 'ui.router']);
app.config(function ($stateProvider, $urlRouterProvider, $urlRouterProvider, $translateProvider, $translatePartialLoaderProvider) {
$stateProvider
// HOME STATES AND NESTED VIEWS ========================================
.state('Registration', {
url: '/Registration',
templateUrl: 'Registration/Registration.html'
});
$translatePartialLoaderProvider.addPart('Main');
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: "Scripts/Locales/{part}/{lang}.json"
});
$translateProvider.preferredLanguage('en_US');
app.run(function ($rootScope, $translate) {
$rootScope.$on('$translatePartialLoaderStructureChanged', function () {
$translate.refresh();
});
});
app.controller('RoslpAppController', ['$scope', '$translate', function ($scope, $translate) {
$scope.clickHandler = function (key) {
$translate.use(key);
};
}]);
});
Whenever i select langualge from the dropdown and click on submit i get Argument RoslpAppController is not a function, got undefined error. May i get some help to fix this error?
Any help would be appreciated. Thank you.
Move the controller outside the app.config.
app.controller('RoslpAppController', ['$scope', '$translate', function ($scope, $translate) {
$scope.clickHandler = function (key) {
$translate.use(key);
};
}]);
routes.js
angular
.module('main')
.config(config);
config.$inject = ['$routeProvider', '$httpProvider'];
function config($routeProvider){
$routeProvider
.when('/', {
templateUrl:'main/views/landing.client.view.html',
controller:'MainController',
controllerAs:'mainCtrl',
resolve: {
orgTypes: orgTypes
}
})
.otherwise({
redirectTo:'/'
});
}
function orgTypes($http){
return $http
.get('emrsvs/orgTypes')
.then(function successCallBack(response){
return response;
}, function errorCallBack(error){
console.log(error);
});
}
controller.js
angular
.module('main')
.controller('MainController', MainController);
MainController.$inject = ['$rootScope', '$timeout', 'orgTypes'];
function MainController($rootScope, $timeout, orgTypes){
var mainCtrl = this;
mainCtrl.orgTypes = orgTypes;
}
Error
[$injector:unpr] Unknown provider: orgTypesProvider <- orgTypes <- MainController
Here i am injecting a dependency 'orgTypes' from route to controller. It produced unknown provider error. Is there anything wrong with my sysntax? can someone find my mistake
you should include following code in routes.js , before orgTypes function definition
angular.module('main')
.factory('orgTypes', orgTypes);
orgTypes.$inject = ['$http'];
/*You need to apply following changes also in controller*/
angular
.module('main')
.controller('MainController', MainController);
MainController.$inject = ['$rootScope', '$timeout', 'orgTypes'];
function MainController($rootScope, $timeout, orgTypes){
var mainCtrl = this;
orgTypes.then(function(response){
mainCtrl.orgTypes = response;
})
}
I can't see anything wrong if you inject the controller with the ng-view directive.
<div ng-app="main">
<ng-view></ng-view>
</div>
Your code works in this JSFiddle.
In your router config, you inject orgTypes from a resolver function. The $routeProvider service injects resolvers as locals into controllers. That method works OK.
If you use the ng-controller directive to load MainController, you will get that error. The $compile service doesn't have access to those resolvers in that case.
I'm doing some interfaces with AngularJS and watching the Chrome Console I detect that each http request to an API it makes for duplicate.
Is there any way to avoid this?
This is my simplified code
$http.jsonp('http://APIURL.com/api/category/menu?callback=JSON_CALLBACK').success(function(data){
$scope.categories=data.categories;
});
Full code:
var kbControllers = angular.module('kbControllers', []);
kbControllers.controller("KBHomeController", function ($scope, $http, $rootScope) {
$rootScope.header = 'Title of page';
$http.jsonp('apicall.com/api/category/menu?callback=JSON_CALLBACK').success(function (data) {
$scope.categories = data.categories;
});
});
and this is my console
any thought?
i have faced this problem, and you can resolve it like this :
check if you have declared ng-controller twice , you need to declare it just one time
check if you have declared data-ng-click , if so , you need to replace it with ng-click
that's it
This is app.js
var app = angular.module('app', [
'ngRoute','kbControllers', 'kbFilters', 'kbDirectives', 'angularytics', 'kbServices'
]).config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: '/assets/angular/kb/partials/home.html',
controller: 'KBHomeController'
}
).when('/category/:category',
{
templateUrl: '/assets/angular/kb/partials/category.html',
controller: 'KBCategoryController'
}
)
.otherwise({redirectTo:"/"});
}
])
And in controllers.js
var kbControllers = angular.module('kbControllers', []);
kbControllers.controller("KBHomeController", function ($scope, $http, $rootScope, Menu) {
$rootScope.header = 'Atención al cliente - Movistar Argentina';
$http.jsonp('http://APIURL.com/api/category/menu?callback=JSON_CALLBACK').success(function(data){
$scope.categories=data.categories;
});
})
and my view /partials/home.html
[...]
<li ng-repeat="category in categories"><i class="{{category.icon}}"></i><span>{{category.name}}</span></li>
[...]
So I am trying to render a subview within a template but I want to define the state inside of the subviews controller on click of an element. The reason for splitting it out from the main controller is that I will be having subviews within the initial subview.
However, I get the following error:
Error: [$injector:modulerr] Failed to instantiate module
ivy.quote.controllers.durationCtrl due to: TypeError: Cannot read
property 'navigable' of undefined
This happens before I have even clicked the button which basically does the following
$state.transitionTo('quote.duration');
quote.tpl.html
<div class="quote grid" disable-scroll>
<div modal-from-bottom modal-hidden="calendarHide"
modal-content-class="quote__keypad" modal-speed="200" ui-view></div>
</div>
quoteCtrl.js
angular.module('ivy.quote.controllers.quoteCtrl', [
'ivy.quote.controllers.keypadCtrl',
'ivy.quote.controllers.durationCtrl',
'ivy.quote.services.quoteManager',
'ui.router',
'ivy.quote.calendar',
'wn.keypad',
'wn.gesture.disableScroll'
])
/**
* Configure UI Router
*/
.config(['$stateProvider', function ($stateProvider) {
$stateProvider.state('quote', {
url: '/quote',
controller: 'quoteCtrl',
templateUrl: 'quote/templates/quote.tpl.html'
});
}])
.controller('quoteCtrl', ['$scope', '$timeout', '$state', 'quoteManager',
function ($scope, $timeout, $state, quoteManager) {
}]);
duration.tpl.html
<div class="quote__calendar">
<h2>DURATION</h2>
<div ui-view></div>
</div>
durationCtrl.js
angular.module('ivy.quote.controllers.durationCtrl', [
'ui.router'
])
.config(['$stateProvider', function ($stateProvider) {
$stateProvider.state('quote.duration', {
url: '/duration',
controler: 'durationCtrl',
templateUrl: 'quote/templates/duration.tpl.html'
});
}])
.controller('durationCtrl', ['$scope', function ($scope) {
console.log('durationCtrl', $scope);
}]);
Your controller should be spelled "controller", not "controler", but otherwise, this looks like all the tutorials I've seen on subviews.
I'm trying to configure my route in such a way to redirect to the login page if user is not logged. This is my code:
angular.module('witBiz.services', []);
angular.module('witBiz.controllers', ['witBiz.services']);
var witBizModule = angular.module('witBiz', ['ngRoute' , 'witBiz.controllers', 'witBiz.services' ]);
witBizModule.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {templateUrl: 'resources/views/login.html', controller: 'LoginController'});
$routeProvider.when('/index', {templateUrl: 'resources/views/index.html', controller: 'IndexController'});
$routeProvider.otherwise({redirectTo: 'resources/views/index.html'});
}])
.run(['$rootScope', 'checkLogin', function($rootScope, checkLogin ,$routeProvider ) {
$rootScope.$on('$routeChangeSuccess', function () {
if (checkLogin())
$location.url("/index");
})
}])
.factory('checkLogin', function(){
return function() {
//perform real logic here
return true;
}
})
where basically I declare modules and services. Now the problem is $location is not defined so I get error.
I tried to inject $location as dependency like this but I got undefined injection (injpt):
.run(['$rootScope', 'checkLogin', '$location', function($rootScope, checkLogin ,$location) {
$rootScope.$on('$routeChangeSuccess', function () {
if (checkLogin())
$location.url("/ciao");
})
}])
So I'm wondering how I can use the builtin $location services inside my "run" method...why can I inject it as a dependency as $rootScope or checkLogin?!
I'm using angular 1.2.0 rc2.
Thanks
Here is a working example http://plnkr.co/edit/gf5LhTjqhz4MoZfVcqIt?p=preview
Couldn't reproduce the error with $location not working inside .run