angular with requirejs - Argument controller is not a function, got undefined - angularjs

I'm trying to use angular with requirejs. Here is my index.html file
<!DOCTYPE html>
<html>
<head>
<script data-main="/js/app.js" src="/bower_components/requirejs/require.js"></script>
</head>
<body >
<div ng-view ng-controller="accountController"></div>
</body>
</html>
app.js file
require.config (
{
appDir : '',
baseUrl : '/js/',
paths :
{
// Configure alias to full paths
'angular': '/bower_components/angular/angular.min',
'ngRoute': '/bower_components/angular-route/angular-route.min',
'main': 'main'
},
shim :
{
'main':{
deps: ["angular", 'ngRoute']
},
'ngRoute':{
deps: ["angular"]
}
}
});
require( [ "main" ], function( app )
{
// Application has bootstrapped and started...
});
main.js file
define([
'common/RouteManager'
], function(RouteManager){
var appName = 'elara',
depends = ['ngRoute'],
app = angular.module(appName, depends).config(RouteManager)
angular.bootstrap(document.getElementsByTagName('body')[0], [ ]);
return app;
});
RouterManager.js
(function ( define ) {
define([
'controllers/account'
], function(){
var RouteManager = $routeProvider.when("/", angularAMD.route({
templateUrl: '/html/tmpl/test.html', controller: 'registerController',
controllerUrl: 'controllers/account.js'
})).otherwise({redirectTo: "/"});
return ["$routeProvider", RouteManager ];
})
});
And finally my controller:
define(['common/settings'], function(settings){
var accountController = function($scope, $http){
$scope.username = "";
$scope.password = "";
$scope.register = function(){
$http.post(config.apiAddress + "account/login/", {username: $scope.username, password: $scope.password}).then(
function(data){
console.log(data);
}, function(response){
console.log(response);
})
}
};
return accountController;
});
I'm getting
Argument 'accountController' is not a function, got undefined
exception. When i check network tab, my account.js file is not loaded. So angular don't know anything about accountController

Brackets
You are returning a function in your controller so it should be
return accountController();
Not
return accountController;

Related

Angular ui-router resolve http empty value

I'm testing a simple angular application and I'm facing some problems. The http GET call is done but resolver renders empty. Here is the code :
A simple index.html :
<html ng-app="myApp">
<head>
//all scripts loaded
</head>
<body ng-controller="myCtrl">
<p>{{test}}</p>
<a ui-sref="tab1">Show Tab 1</a>
<a ui-sref="tab2">Show Tab 2</a>
<a ui-sref="tab3">Show Tab 3</a>
<ui-view></ui-view>
</body>
</html>
The app.js :
var app = angular.module('myApp', ['ui.router']);
app
.service('DataService', function ($http) {
return {
getData: function() {
return $http({
method : "GET",
url : "/hi"
}).then(function(response) {
return response.data;
},function(response) {
return "error";
});
}
}
});
app
.controller('myCtrl', function($scope) {
$scope.test = "Test";
});
app
.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('tab1', {
url: '/tab1',
templateUrl: '/assets/templates/tab1.html'
})
.state('tab2', {
url: '/tab2',
templateUrl: '/assets/templates/tab2.html'
})
.state('tab3', {
url: '/tab3',
templateUrl: '/assets/templates/tab3.html'
resolve:{
mydata : function (DataService) {
return DataService.getData();
}
},
controller: 'myCtrl'
});
$urlRouterProvider.otherwise('/tab1');
});
Tab3 template :
<p>Data: {{mydata}}</p>
As I said, when I click the "tab3" link, the http get call is done, and a JSON data is retrieved, but "mydata" is rendered to blank.
Any clue??
Thanks and regards.
Your controller doesn't do anything with mydata. So it's not in the scope, so the view can't display it. It should be:
app.controller('myCtrl', function($scope, mydata) {
$scope.mydata = mydata;
});

Angular JS with Require JS

I am using requireJs with Angular Js , Into my require-config file i bootstrapped the application as follows:
require([
'angular',
'app'
], function(angular, app) {
// alert('sd');
var $html = angular.element(document.getElementsByTagName('html')[0]);
angular.element().ready(function() {
// bootstrap the app manually
angular.bootstrap(document, ['iStickers']);
alert('test');
});
}
when I am trying to use the function to change language in my application,
'use strict';
define([
'angular',
'angularRoute',
// 'resource'
], function(angular) {
alert('ww');
var loginModule = angular.module('iStickers.login',['ngRoute','ngResource'])
loginModule.service('translationService',[ function($resource) {
alert('3');
this.getTranslation = function($scope, language) {
var languageFilePath = 'translation_' + language + '.json';
console.log(languageFilePath);
$resource(languageFilePath).get(function(data) {
$scope.translation = data;
});
};
}]);
loginModule.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'views/login/login.html',
controller: 'loginCtrl'
});
}])
loginModule.controller('loginCtrl', 'translationService', ['$scope', function($scope, translationService) {
$scope.selectedLanguage = 'no';
$scope.translate();
}]);
it gives me an error:
Error: [ng:areq] Argument 'loginCtrl' is not a function, got string
http://errors.angularjs.org/1.3.8/ng/areq?p0=loginCtrl&p1=not%20a%20function%2C%20got%20string
minErr/<#https://code.angularjs.org/1.3.8/angular.js:63:12

appCtrl is not a function, got undefined error triggered when trying to load appCtrl (ON THE FLY)

I want to load controllers on the fly when needed rather than loading them in one go. So, for the I've implemented dynamic approach which works fine without any error. It also works well with Ui-Router.
But the problem is in Index.html page. I want to put global (super parent) controller name "appCtrl". As this appCtrl should be initialized when I run my app. For that I need to write like ng-controller="appCtrl" or ng-controller="appCtrl as vm" at body tag.
But when I do it, it gives error that appCtrl is a function, got undefined. I tried sever ways but still unable to identify exact error. I have working on this issue since two to three days but still not able to identify it.
I have made this plunker.
look at body tag of index.html.
main.js
require.config({
paths: {
"angular": "//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0-rc.1/angular",
"ui-router": "//rawgit.com/angular-ui/ui-router/0.2.15/release/angular-ui-router"
},
shim: {
"angular": {
exports: 'angular'
},
"ui-router": {
deps: ['angular']
}
}
});
define(
['angular',
'app',
'controllers/appCtrl'],
function (angluar, app) {
angular.bootstrap(document, ['MyApp'])
});
app.js
define([
'angular',
'ui-router'
], function (angular) {
var app = angular.module('MyApp', ['ui.router']);
function lazy () {
var self = this;
this.resolve = function (controller) {
return {
ctrl: ['$q', function ($q) {
var defer = $q.defer();
require(['controllers/' + controller], function (ctrl) {
app.register.controller(controller, ctrl);
defer.resolve();
});
return defer.promise;
}]
};
};
this.$get = function (){
return self;
};
}
function config ($stateProvider, $urlRouterProvider,
$controllerProvider, $compileProvider,
$filterProvider, $provide, lazyProvider) {
$stateProvider
.state("home", {
url: "/",
controller: 'homeCtrl',
controllerAs: 'vm',
templateUrl: 'views/homeView.html',
resolve: lazyProvider.resolve('homeCtrl')
});
app.register = {
controller: $controllerProvider.register,
directive: $compileProvider.directive,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service,
constant: $provide.constant
};
}
app.provider('lazy', lazy);
app.config(config);
return app;
});
Index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.17/require.js" data-main="main.js"></script>
</head>
<body ng-controller="appCtrl as vm"> // I want this to work correctly but it is not getting loaded dynamically. I don't know why. Help me to resolve it.
<a ui-sref="home">go home</a>
<ui-view></ui-view>
{{vm.appVar}}
</body>
</html>
You are actually missing the controller statement in your controller code.
Use the following code
define(['app'], function (app){ //Updated Line
console.log('app controller loaded');
app.controller('appCtrl',ctrl); //New Line added
ctrl.$inject = ['$http'];
function ctrl ($http) {
this.appVar = 'hi from appCtrl';
};
return ctrl;
});
See the plunker

Angularjs + Requirejs error with filter

I trying to add angularjs filter with requirejs in my view, but I receive an error:
Error: $injector:unpr Unknown Provider
http://docs.angularjs.org/error/$injector/unpr?p0=localizationFilterProvider%20%3C-%20localizationFilter
Whats wrong?
My Files:
index.html
<!DOCTYPE html>
<html>
<head>
<script data-main="/static/js/application/main" src="/static/js/libs/require.min.js"></script>
</head>
<body>
<div class="page" ng-view></div>
</body>
</html>
app.js
'use strict';
define(
[
'angularAMD',
'angular-route',
'angular-animate'
],
function (angularAMD) {
var app = angular.module('FilmOrder', ['ngRoute', 'ngAnimate']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/',
angularAMD.route({
templateUrl: 'static/js/application/views/success.html',
controllerUrl: 'application/controllers/Success',
controller: 'Success'
})
)
.otherwise({redirectTo: '/'});
}]);
angularAMD.bootstrap(app);
return app;
});
main.js
require.config({
baseUrl: "static/js",
paths: {
'angular': 'libs/angular.min',
'angular-route': 'libs/angular-route.min',
'angular-animate': 'libs/angular-animate.min',
'angularAMD': 'libs/angularAMD.min'
},
shim: {
'angularAMD': ['angular'],
'angular-route': ['angular'],
'angular-animate': ['angular']
},
deps: ['application/app']
});
views/success.html
<div class="success">
<div class="success_head">
{{"Пожалуйста, убедитесь в правильности указанных данных." | localization:'index'}}
</div>
</div>
filters/localization.js
'use strict'
define(['application/app'], function (app) {
app.filter('localization', function () {
return 'test';
});
});
controllers/Success.js
define(
[
'application/app',
'application/filters/localization',
'application/services/Application'
],
function (app) {
'use strict';
app.register.controller('Success', function ($scope) {
var Success = {};
$scope.Success = Success;
});
});
Your filter is called after bootstrapping so you should be using app.register instead:
filters/localization.js
define(['application/app'], function (app) {
'use strict'
app.register.filter('localization', function () {
return 'test';
});
});
If this does not help, setup a plunker and I will try to help further.

AngularJS $routeProvider.when() 's resolve route parameter - what is that 'key'?

AngulaR resolve API
The API says for resolve:
key – {string}: a name of a dependency to be injected into the controller.
#egghead, there is this video on the topic:
egghead - Angular resolve
What i do not understand is what that key object is for and why the author of the above video does inject the controller into itself
key – {string}: a name of a dependency to be injected into the
controller.
app.config(function($routeProvider) {
$routeProvider.
when('/', {
controller: 'ListCtrl',
resolve: {
myResolve: function(MyService) {
return MyService();
}
},
templateUrl:'./views/list.html'
})
});
Instead of (in the controller)
app.controller('MyController',function($scope,MyService){
$scope.data = MyService();
});
if you use resolve
app.controller('MyController',function($scope,myResolve){
$scope.data = myResolve;
});
UPDATE
a working example
<!doctype html>
<html ng-app="myModule">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="content" data-ng-view=""></div>
<script src="http://code.angularjs.org/1.0.8/angular.min.js"></script>
<script>
var myModule = angular.module('myModule', []);
myModule.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: './index.html',
controller: 'IndexCtrl',
resolve: {
hello: function(Hello) {
return Hello.getMessages();
}
}
})
.otherwise({
redirectTo: '/'
});
});
myModule.factory('Hello', function($q, $timeout) {
var getMessages = function() {
var deferred = $q.defer();
$timeout(function() {
deferred.resolve('Hello');
}, 1000);
return deferred.promise;
};
return {
getMessages: getMessages
};
});
myModule.controller('IndexCtrl',function($scope,hello){
$scope.hello = hello;
});
</script>
</body>
</html>
the view
<p>{{hello}}</p>

Resources