I have module with directive and application which is module with controllers.
angular.module('ValidationWidgets', [])
.directive('validationfield', function () {
....
});
angular.module('MyPage', ['ValidationWidgets'])
.controller('MyFirstController', function ($scope) {
....
});
Is there some pretty syntax to declare many controllers in app module, because .controller('MyFirstController', function ($scope) { looks bad?
I want to write something like:
var myPage = angular.module('MyPage', ['ValidationWidgets']);
myPage.controllers.MyFirstController = function($scope) {
...
}
var app = angular.module("myApp", []);
app.controller("my controller", function(){});
or
var app = angular.module("myApp", []);
var controllers = {};
controller.myController = function(){};
app.controller(controllers);
Take a look at this video http://egghead.io/video/angularjs-thinking-different-about-organization/
The whole series is amazing to be honest.
To expand on what #Jacob Dalton said, you can do this:
Setup your routes:
app.config(['$routeProvider', function($routeProvider, $locationProvider) {
$routeProvider.
when('/view1', {templateUrl: 'partials/view1', controller: 'View1Ctrl'}).
when('/view2', {templateUrl: 'partials/view1', controller: 'View2Ctrl'}).
otherwise({redirectTo: '/view1'});
}]);
Then you can declare your controllers by simply declaring a function:
function View1Ctrl($scope, $http) {
}
function View2Ctrl($scope, $http) {
}
Those functions will be auto wired as controllers. As stated before, however, this makes it less obvious that these functions are controllers.
Related
This is my ngRoute (AngularApp.js)
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider, $locationProvider){
$routeProvider.
when('/register', {templateUrl: 'partials/AdminPage/register.html', controller: 'registerCtrl'}).
when('/updateEmployee', {templateUrl: 'partials/AdminPage/updateEmployee.html', controller: 'updateEmployeeCtrl'}).
when('/designers',{templateUrl: 'partials/CreateSurvey/design.html',controller: 'DesignCtrl'});
});
This is Another js file where my other controllers are (AngularApp2.js)`
var app = angular.module("myApp", []);
app.controller('myController',function($scope,$http){
$http.get('data.json').success(function(response){
$scope.myData = response;
});
$scope.removeName = function(row) {
$scope.myData.splice($scope.myData.indexOf(row),1);
}
});
But when I include both angular code in one file as below, the 'myController' is not working.
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider, $locationProvider){
$routeProvider.
when('/register', {templateUrl: 'partials/AdminPage/register.html', controller: 'registerCtrl'}).
when('/updateEmployee', {templateUrl: 'partials/AdminPage/updateEmployee.html', controller: 'updateEmployeeCtrl'}).
when('/designers',{templateUrl: 'partials/CreateSurvey/design.html',controller: 'DesignCtrl'});
});
app.controller('myController',function($scope,$http){
$http.get('data.json').success(function(response){
$scope.myData = response;
});
$scope.removeName = function(row) {
$scope.myData.splice($scope.myData.indexOf(row),1);
}
});
What is the error I am making?
You have 2 different modules app and myApp but never inject one as dependency of the other
Assuming your ng-app uses app as main module you need to inject the myApp module into app one, or make both names the same so you only have one module
Problem is you have
var app = angular.module('app', ['ngRoute']);
it shoud be
var app = angular.module('myApp', ['ngRoute']);
Also make sure you use the ng-app="app" in the HTML if you are declaring as first way.
DEMO
I am working on an app about routing, my code:
//HTML, I passed a 'test' into routing
Test
<div data-ng-view=""></div>
//Template
<h1>{{res}}</h1>
//Angularjs
var app = angular.module("dictApp", ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/details/:test', {
templateUrl: 'template.html',
controller: 'testCtrl'
});
}]);
app.controller('testCtrl', function ($scope, $routeProvider) {
$scope.res = $routeProvider.test;
});
//The template is displayed as
{{res}}
The template page should display 'test', but I don't know why it didn't work.
Thansk in advance.
'test' parameter should be available in $routeParams.
app.controller('testCtrl', function ($scope, $routeParams) {
$scope.res = $routeParams.test;
});
The service that exposes the route parameters is $routeParams. $routeProvider is the provider used to configure the routes in the app like the one you have done in your code using .when method as well
You need to inject $routeParams and use it instead of $routeProvider
app.controller('testCtrl', function ($scope, $routeParams) {
$scope.res = $routeParams.test;
});
The app runs on http://domain1 an must request data from http://domain2 with the following code:
'use strict';
// Declare app level module which depends on views, and components
var myApp = angular.module('myApp', [
'ngRoute',
'restangular'
]);
myApp.config(['$routeProvider', 'RestangularProvider', function($routeProvider, RestangularProvider) {
$routeProvider.when('/view1', {
templateUrl: '/view1.html',
controller: 'View1Ctrl'
});
$routeProvider.otherwise({redirectTo: '/view1'});
RestangularProvider.setBaseUrl("http://domain2/");
}]);
var rest = null;
myApp.controller('View1Ctrl', ['$scope', 'Restangular', function($scope, Restangular) {
rest = Restangular;
var cursos = Restangular.one("resource",100).get()
}]);
Nonetheless, the request goes to http://domain1. What is going on? I also inspected the Restangular configuration, by putting Restangular in the global scope, as the rest variable, and the base url seems is property set.
Hey you can create a factory and use different domain to get data something like below
(function () {
'use strict';
angular.module('app')
.factory('Domain2Restangular', ['Restangular', Domain2RestangularFunction]);
function Domain2RestangularFunction( Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
var baseURL = 'http://domain2';
RestangularConfigurer.setBaseUrl(baseURL);
RestangularConfigurer.setDefaultHeaders({'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' });
});
}
}());
You can invoke
return Domain2Restangular.all('')
.post(data)
.then(function(response) {
return response;
}, function(error) {
return error
});
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.
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',...