This is my first attempt to create a sample angular application.
In app.js I defined the following -
var app = angular.module('myTestApp', ['ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch']);
app.config(function ($routeProvider) {
routeProvider
.when('sample', {
templateUrl: 'views/sample.html',
controller: 'sampleCtrl'
})
});
I have created corresponding sample.js for controller, sample.html for template and sampleModel.js for model.
In grunt console, it throws app is not defined in controller and model file
Here is the controller file -
'use strict';
app.controller('SampleCtrl', function ($scope,
$location,
$routeParams,
SampleModel) {
console.log('this is a test controller');
});
All the files are included in index.html and the resources are loading correctly which I checked by chrome developer tool but I can't find the reason why it says app not defined. Is there anything I am missing?
As they are separate files and grunt/jshint will not know that the variable is available in other files. Instead of that it would be a best practice to use it in this way:
Instead use this:
angular.module('myTestApp')
.controller('SampleCtrl', function ($scope,
$location,
$routeParams,
SampleModel) {
console.log('this is a test controller');
});
Another general pattern you might have noticed in most the other's code, wrapping the code inside an IIFE.
(function() {
"use strict";
var app = angular.module('myTestApp')
app.controller('SampleCtrl', function ($scope,
$location,
$routeParams,
SampleModel) {
console.log('this is a test controller');
});
})();
In this app will not pollute the global namespace and it's local to that function.
Here if you've noticed, I've not used [] while using angular.module(), it means that we're just getting that module.
So in your app.'s alone, it will be with [] and in other files without []
(function() {
"use strict";
var app = angular.module('myTestApp', ['ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch']);
app.config(function ($routeProvider) {
$routeProvider
.when('sample', {
templateUrl: 'views/sample.html',
controller: 'sampleCtrl'
})
});
})();
If everything else is fine, this line is causing the issue in your code -
app.config(function ($routeProvider) {
routeProvider
you should instead use -
app.config(function ($routeProvider) {
$routeProvider
And yes, if var app is not working, try using
angular.module('myTestApp')
.controller('SampleCtrl',...
Related
I'm new using Angular with MVC Web Api but using VB instead of C#. I'm trying to make an SPA web site and I have some week trying to solve this problem.
In my app.js I defined the routing to my views and the controllers I'm going to use in them
var goMessage = angular.module('goMessage', ['ngRoute', 'goMessage.controllers', 'goMessage.services', 'goMessage.directives']);
angular.module('goMessage.controllers', []);
angular.module('goMessage.services', []);
angular.module('goMessage.directives', []);
goMessage.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
//Vista Login
$routeProvider.when('/login/inicio', {
controller: 'loginController',
controllerAs: 'lgCtrl',
templateUrl: 'Home/Login'
});
//Vista Usuarios
$routeProvider.when('/usuarios/lista', {
controller: 'usuariosController',
controllerAs: 'usCtrl',
templateUrl: 'Home/Usuarios'
});
$routeProvider.when('/dashboard/inicio', {
controller: 'dashboardController',
controllerAs: 'dashCtrl',
templateUrl: 'Home/Dashboard'
});
$locationProvider.html5Mode(true);
}]);
The usuariosController.js controller is working very well, its code is:
angular.module('goMessage.controllers')
.controller("usuariosController", ['$scope', '$http', 'ws', '$window', '$timeout', '$route',
function ($scope, $http, ws, $window, $timeout, $route) {
//DeclaraciĆ³n de variables
var me = this;
//Ordenamiento por default
this.ordenarPorColumna = 'UsuarioID';
this.reverse = false;
// More code...
}
]);
And the loginController.js controller code is:
angular.module('goMessage.controllers')
.controller('loginController', ['$scope', '$http', 'ws', '$window', '$timeout', '$route',
function ($scope, $http, ws, $window, $timeout, $route) {
//DeclaraciĆ³n de variables
var me = this;
this.myData = "Data$$$";
}
]);
In the Login.vbhtml view I'm following the same pattern as the Usuarios.vbhtml view. I define my ng-app in the _layout.vbhtml and I don't define any controller inside any view.
The error I'm unable to solve is this:
Error Image
Look at the AngularJs Expression
As you can see, I've defined both controller using the same way but the only one that works is the usuarios one and any other controller I add doesn't work.
Here I show you the scripts loading order:
Scripts Loading Order
I'm using my local IIS and working in VS2012.
The angular JS version is 1.6.
To register the logic modules as controller, filter and etc..., you need to add this code in your app.config
var app = angular.module("App", []);
var config = function ($controllerProvider, $compileProvider, $filterProvider, $provide) {
app.controller = $controllerProvider.register;
app.directive = $compileProvider.register;
app.filter = $filterProvider.register;
app.factory = $provide.factory;
app.service = $provide.service;
app.constant = $provide.constant;
//your codes
}
config.$inject = ["$controllerProvider", "$compileProvider", "$filterProvider", "$provide"];
app.config(config);
Why this happen?
sometimes we don't need to add all of controllers in our main index which has ng-view or ui-view for that we should put our controller as lazyload to the app.config as you do this in your config, because of that the main app for get the controllers need to register controllers and other modules.
This issue might happen due to asynchronous loading of scripts. The script order might also be an issue. You can add a console.log at the beginning of loginController to check whether the component is loaded correctly.
I am getting javascript run time error
myApp is undefined
for my angular service. Don't know what wrong im doing here..
This is how i defined my app.js
app.js
var myApp = angular.module('myApp', [
'ngRoute', 'motorControllers', 'motorDetailsController', 'motorServices', 'ngSanitize', 'ui.select', 'ngResource',]);
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/motors', {
templateUrl: 'View/motorList.html',
controller: 'motorController'
}).
when('/motors/:Id', {
templateUrl: 'View/motorDetails.html',
controller: 'motorDetailsController'
}).
otherwise({
redirectTo: '/motors'
});
}]);
This is how i am creating/calling myApp in controller.
Controller
angular.module('myApp', []).controller('motorController', function ($scope, motorService) {
//////
}
This is how i am trying use myApp in my service. but it gives error myApp is undefined.
Service:
myApp.service('motorService', ['$http', function ($http) {
//////
}
and this is how i declared it in my html
<html ng-app="myApp">
Looking forward for some help.
Thanks
I think that the error is in the controller's declaration, because you're defining the app 'myApp' twice.
angular.module('myApp', []).controller('motorController', function ($scope, motorService) {
//////
}
should be
angular.module('myApp').controller('motorController', function ($scope, motorService) {
//////
}
Edit
#simbada
It's up to you. You can separate them in different modules.
(function(angular){
angular
.module('myApp', ['myApp.Controllers']);
angular
.module('myApp.Services', [])
.service('mySrv', function($http){
function _get(){
return $http.get('url');
}
return {
get: _get
}
});
angular
.module('myApp.Controllers', ['myApp.Services'])
.controller('myCtrl', function($scope, mySrv){
$scope.var = 'Hello';
});
})(angular);
You have passed comma in dependancy after ngResource just remove that it'll work fine.
var myApp = angular.module('myApp', [
'ngRoute', 'motorControllers', 'motorDetailsController', 'motorServices', 'ngSanitize', 'ui.select', 'ngResource']);
I think this should be
angular.module('myApp').controller('motorController', function ($sc...
whitout [ ] brackets.
also see how you declare your service:
var myApp = angular.module('myApp', [
'ngRoute', 'motorControllers', 'motorDetailsController', 'motorServices', 'ngSanitize', 'ui.select', 'ngResource']);
when your service is 'motorService'
Your service should be:
myApp = angular.module('motorServices');
myApp.service('motorService', ['$http', function ($http) {
//////
}
if I have the following angularjs code route provider how can I pass through a dependency into the blaCtrl controller please?
Many thanks,
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/bla', { templateUrl: 'bla.html', controller: 'blaCtrl' });
trying to get something like
'use strict';
app.controller('blaCtrl', function ($scope) {
$scope.mydata = ['111', '222', '333']; // how can I change this to be a method call to a dependency, i.e.
$scope.mydata = mydependency.getData(); // example what I need
});
update
My app file looks like this - I'm still not getting the data displayed?
'use strict';
var app = angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/application', { templateUrl: 'partials/application.html', controller: 'myCtrl' });
$routeProvider.otherwise({ redirectTo: '/application' });
}]);
controller
'use strict';
app.controller('myCtrl', 'myService', function ($scope, myService) {
debugger; // doesn't get hit?
$scope.stuff = myService.getStuff();
});
console error
- I get this error in the console Error: [ng:areq] http://errors.angularjs.org/1.4.5/ng/areq?p0=applicationCtrl&p1=not%20a%20function%2C%20got%20string
There are 3 ways of dependency annotation according to angular docs.
Inline Array Annotation
In this case your controller defenition should look like:
'use strict';
app.controller('blaCtrl', ['$scope', 'mydependency', function ($scope, mydependency) {
$scope.mydata = mydependency.getData();
}]);
$inject Property Annotation
'use strict';
var blaCtrl = function ($scope, mydependency) {
$scope.mydata = mydependency.getData();
};
blaCtrl.$inject = ['$scope', 'mydependency'];
app.controller('blaCtrl', blaCtrl);
Implicit Annotation
This one you used in your example code to inject $scope variable. Not recommended, minificattion will broke such code.
'use strict';
app.controller('blaCtrl', function ($scope, mydependency) {
$scope.mydata = mydependency.getData();
});
The fact that you reference your controller not in HTML but in routeProvider doesn't make any difference.
You can pass a dependency to the controller from within the controller. You're injecting the $scope dependency already, and you can inject others like $location and $rootScope if you'd like.
I'm just about to write tests for my angularjs-app. However when Im trying to run the test which is very simpel one i get the following error.
Error: [ng:areq] Argument 'MyPageController' is not a function, got undefined
I'll provide code for the setup of my controllers, config etc.
Route
var myPageApp = angular.module('myPageApp', ['ngRoute', 'ngAnimate', 'ngSanitize', 'app.controller', 'app.service', 'app.filter', 'app.config'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'App_AngularJs/partials/myPage/myPage.htm',
controller: 'MyPageController',
reloadOnSearch: false,
});
}]);
Controller
var myPageApp = angular.module('app.controller', ['oci.treeview', 'ui.bootstrap'])
.controller('MyPageController', ['$scope', '$routeParams', '$location', '$timeout', '$filter', '$modal', 'myPageService',
function ($scope, $routeParams, $location, $timeout, $filter, $modal, myPageService) {
init();
function init() {
$scope.page = { value: $routeParams.page || 1 };
}
}]);
Simpel test
'use strict';
describe('Testing MyPageController', function(){
var scope;
//mock Application to allow us to inject our own dependencies
beforeEach(angular.mock.module('myPageApp'));
//mock the controller for the same reason and include $rootScope and $controller
beforeEach(angular.mock.inject(function($rootScope, $controller){
//create an empty scope
scope = $rootScope.$new();
//declare the controller and inject our empty scope
$controller('MyPageController', { $scope: scope });
}));
// tests start here
it('should map routes to controllers', function () {
module('myPageApp');
inject(function ($route) {
expect($route.routes['/'].controller).toBe('MyPageController');
expect($route.routes['/'].templateUrl).
toEqual('App_AngularJs/partials/myPage/myPage.htm');
});
});
it('should have variable assigned = "1"', function(){
expect(scope.page.value).toBe(1);
});
});
My wildest and best guess is that i need to mock app.controller but how? Everything starts out with myPageApp which holds references to service, controller etc etc..
I think your issue is that routing and the controller are trying to load different modules viz "myPageApp" and "app.controller" and in your test with beforeEach you are trying to load 'myPageApp' module to which router is associated but not the controller.
So it seems to me that either you use same module for both router and controllers. Or try loading both modules in the test. Still I believe associating the router and controller with same module makes more sense.
An small example as below. Extract the application module in common js file (may be call it app.js)
var myApp = angular.module(
'myApp');
Now define router as
myApp.config(function ($routeProvider) {
$routeProvider
.when('/testUrl', {
templateUrl: '/myApp/views/test-view',
controller: 'TestViewController'
})
Similary define controller as
myApp.controller('TestViewController',[your dependencies goes here])
And now in your tests
beforeEach(module('myApp'));
This will work for sure. Hope it helps.
I have two moudules:
var app = angular.module('app', ["homeModule"])...
angular.module("homeModule", [])...
and if in web config property "compilation debug="true".." everything works fine.
But when I build the project in release and "compilation debug="false".."
BundleCollection collects all JS files in one I have problem.
In log console i see error
Error: Unknown provider: n from homeModule
My "app" module can not find and connect "homeModule".
What am I doing wrong? How do I properly connect the "homeModule" module ?
I think you have problem with AngularJs and minification in general. When defining dependencies you need to use array notation, for example:
angular.module("app", ["homeModule"])
.controller("UsersController", ["$scope", "usersRepository", function($scope, usersRepository) {
// ...
}]);
or use https://github.com/btford/grunt-ngmin which makes conversion for you.
I found problem in homeModule.config
Worked code:
var app = angular.module('app', ["homeModule"]);
app.config(['$routeProvider', '$locationProvider',function ($routeProvider, $locationProvider)
{
$locationProvider.html5Mode(true);
$routeProvider.otherwise({ redirectTo: '/' });
}
]);
angular.module("homeModule", [])
.config(['$routeProvider', function ($routeProvider)
{
$routeProvider.when('/', { templateUrl: 'ClientApp/Home/Index.html' });
$routeProvider.when('/home', { templateUrl: 'ClientApp/Home/Index.html' });
}])