Unable to fix Argument Controller is not a function, got undefined - javascript

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);
};
}]);

Related

AngularJS Controller in route is not called

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

Connecting ng-click to controller function

I am having trouble getting a partial's div's ng-click attribute to fire the function I want, called testDivClicked().
In my application controller, I provide a route to a partial called test:
(function () {
"use strict";
angular
.module('myApp', ['ngRoute', 'ui.bootstrap', 'myApp.main', 'myApp.test'])
.config(config);
config.$inject = ['$routeProvider'];
function config($routeProvider) {
$routeProvider
.when('/', {templateUrl: '/partials/main.html', controller: 'MainController', controllerAs: 'vm'})
.when('/test', {templateUrl: '/partials/test/test.html', controller: 'TestController', controllerAs: 'vm'})
.otherwise({redirectTo: '/'});
}
})();
Here is the test.html partial that gets inserted into the parent view:
<div class="outer-holder test-outer-holder">
<div class="middle-holder test-middle-holder">
<div class="inner-holder test-inner-holder">
<div class="test-container" ng-click="vm.testDivClicked('test-container')">
<legend>Test</legend>
</div>
</div>
</div>
</div>
My test controller:
(function () {
"use strict";
angular
.module("myApp.test")
.controller("TestController", TestController);
TestController.$inject = [];
function TestController() {
var vm = this;
function testDivClicked(msg) {
console.log("message:", msg);
}
}
})();
When I click on the innermost div, I would like testDivClicked() to log that I clicked on it.
What am I missing in this setup, that would allow me to get ng-click to work?
You should write vm.testDivClicked = function(msg) not function testDivClicked. You declared a local function.
The module name myApp.test provided for creating controller is wrong. Instead use angular.module("myApp")
So your test controller should be
(function () {
"use strict";
angular
.module("myApp")
.controller("TestController", TestController);
TestController.$inject = [];
function TestController() {
var vm = this;
function testDivClicked(msg) {
console.log("message:", msg);
}
}
})();
As said earlier by Alexander, the function testDivClicked function is not associated with vm(this). so it is not recognized in the dom as vm.testDivClicked('test-container').
Here is the modified portion.
function TestController() {
var vm = this;
vm.testDivClicked = function(msg) {
console.log("message:", msg);
}
}

Angular Controllers Firing off more than once. Only certain ones

I have markup that has the following and then I have different sections of the app defined in different files. The problem I am running into is that the controllers that are on the main app page on load causes each of the nested controllers to run more than once. Any states that I change to with a click of the button are fine but these fire off 2-3 times each.
<html ng-app="myApp">
<body ng-controller="myController">
<div ng-controller="dashController">
<div ng-controller="listController">
</div>
</div>
</body>
</html>
My App.js
var myApp = angular.module('myApp', [
'user.profile',
'myApp.controllers',
'myApp.directives',
'ngCookies',
'ngAutocomplete',
'ui.router'
]).config(function($stateProvider, $urlRouterProvider, $locationProvider, $interpolateProvider) {
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
$urlRouterProvider.otherwise('/');
$stateProvider.
state('app', {
url: '/app',
templateUrl: '/views/homepage',
controller: 'MyCtrl1'
});
$locationProvider.html5Mode(true);
});
myApp.controllers
angular.module('myApp.controllers', ['ui.router','ngCookies']).
controller('myController', function ($scope, $http,$cookies) {
$scope.message = 'nothing to see here, move along';
if ($cookies.userdata) {
$cookies.userdata = $cookies.userdata.replace("j:", "");
console.log($cookies);
}
});
user.profile.js
angular.module('user.profile', [
'user.controllers',
'ngAnimate',
'ngCookies',
'ngResource',
'ngSanitize',
'nouislider',
'ui.router',
'ui.bootstrap',
'ngLinkedIn'
])
.config(function($stateProvider, $urlRouterProvider, $locationProvider,$interpolateProvider, $linkedInProvider) {
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
$linkedInProvider.set('appKey', '753pos06f998t3')
.set('scope', 'r_fullprofile');
//.set('authorize', true);
$locationProvider.html5Mode(true);
$stateProvider
.state('userDashboard', {
controller: 'dashController'
})
.state('userList', {
views : {
'popup' : {templateUrl: '/views/app/user/list/userList'}
},
controller: 'listController'
});
});
user.controllers.js
angular.module('user.controllers', ['ui.router', 'ngAutocomplete', 'nouislider', 'ui.bootstrap', 'ngCookies', 'ngLinkedIn', 'angularFileUpload','cgPrompt'])
.directive('onLastRepeat', function () {
return function (scope, element, attrs) {
if (scope.$last) setTimeout(function () {
scope.$emit('onRepeatLast', element, attrs);
}, 1);
};
}).
controller('dashController', function ($scope, $state, $modal, $log, $http, $cookies) {
$scope.user = [];
}).
controller('listController', function ($scope, $http, $cookies) {
});
My app also doesn't initialize unless I run angular.bootstrap(document, ["myApp"]);
I don't think it is having the controller defined in the $stateProvider and the DOM... if I remove from the DOM none of the ng-clicks work even after the controller fires... also I have an ng-click that changes the state and it's controller is defined in the stateProvider and in the DOM and it does not fire twice... what is does is kick off the two other controllers again first before proceeding with it's action though.
The issue is that you are defining your controllers with the routeProvider / stateProvider ie:
$stateProvider.state('userDashboard', {
controller: 'dashController'
})
.state('userList', {
views : {
'popup' : {templateUrl: '/views/app/user/list/userList'}
},
controller: 'listController'
});
an you are redifining them in the DOM using
<div ng-controller="dashController">
remove one or the other but don't use the two at the same time, I'd suggest to remove the one declared in the DOM, ng-controller="dashController"
cheers

AngularJS duplicates http requests

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>
[...]

Subviews in Angular

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.

Categories