I'm learning angular.js, and wonder when app.controller("MyCtrl",...) should be used and when function MyCtrl($scope){...} should be used.
I see no big differences between the two approaches in this example (link to a plunker):
index.html:
<body ng-app="myApp">
<div ng-controller="FirstCtrl as app1">
<button class="btn" ng-model="app1.count"
ng-click="app1.increment()">
Click to increment</button>
{{ app1.count }}
</div>
<div ng-controller="SecondCtrl">
<button class="btn" ng-model="count"
ng-click="increment()">
Click to increment</button>
{{ count }}
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>
<script type="text/javascript" src="example.js"></script>
</body>
example.js:
var app = angular.module("myApp", []);
app.controller("FirstCtrl",function () {
this.count = 0;
this.increment = function (){
this.count = this.count + 1;
}
});
function SecondCtrl($scope){
$scope.count = 0;
$scope.increment = function (){
$scope.count = $scope.count + 1;
}
}
The major reasons for using the module based controller declaration are
Support for minification. The second approach breaks when you minify the code as Dependency Injection fails.
JavaScript good practice is to minimizing polluting the global namespace and the first syntax help there.
In both of your usages, the recommended approach is to inject $scope and use that (rather than using this, which you can do in the second approach as well).
The difference between approach one and two is in how to support minification. In the former, you can supply an array of injected arguments, whereas in the latter you modify $inject. This is of course a bit technical but it is highly recommended to support minification. See A note on minification in the documentation.
The former also does not name the function in the global scope, which is generally a good thing!
Typically, when you create an application you need to set up an initial state for an Angular scope.
Angular applies (in the sense of JavaScript's Function#apply) the controller constructor function to a new Angular scope object, which sets up an initial scope state. This means that Angular never creates instances of the controller type (by invoking the new operator on the controller constructor). Constructors are always applied to an existing scope object.
You set up the initial state of a scope by creating model properties. For example:
function GreetingCtrl($scope) {
$scope.greeting = 'Hola!';
}
The GreetingCtrl controller creates a greeting model which can be referred to in a template.
NOTE: Many of the examples in the documentation show the creation of functions in the global scope. This is only for demonstration purposes - in a real application you should use the .controller method of your Angular module for your application as follows:
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingCtrl', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
}]);
Note also that we use the array notation to explicitly specify the dependency of the controller on the $scope service provided by Angular.
For more detail Read this
Related
I have a simple angular snippet
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="name">
<h1>My name is {{name}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
$scope.age = "26";
$scope.height = "5.9";
$scope.gender = "M";
});
</script>
As you can see I have 4 variables declared in my myCtrl controller
$scope.name = "John Doe";
$scope.age = "26";
$scope.height = "5.9";
$scope.gender = "M";
Is there a way to programmatically list of all the declared $scope variables of a specific angular controller?
Why am I trying to do this ?
Sometimes, when you’re deep in 1000 lines of code in an angular controller, it will be very helpful to know what are the available variables to use at that specific moment. First, the benefit would be, so we don’t re-declare something that already been declared, and second, so we don't override an existing variable unintentionally. For those 2 reasons alone, that's why I am trying to list all the available $scope variables, especially the one that I declared in on that specific page, or in a specific controller of Angular.
NOTE : I am NOT looking to list all JS scope variables, but only looking for those one that I declared in Angular
I know exactly what you need and I use this lib extensively to show me my objects like Chrome does.
Angular json formatter
And the beauty is that it updates instantly with Angular magic. So you know the current state of your object at all times!
Simply drop this directive in your html and assign $scope to it.
In my mine file I have the div with ng-view and it is loaded with the some template. Inside the temp`late I have a button which will change the value.
after to click the button, I am trying to show the value in the index but I recieving a null value.
In index.html I could have something like:
<html>
...
<body ng-app="productsApp" ng-Controller="mycontroller">
<div ng-view></div>
{{value}}
</body>
</html>
In my controller I have something like
angular.module('productsApp').controller('ProductController',
['$scope', 'dataService', function ($scope, dataService) {
$scope.value;
$scope.button = function () {
$scope.value= "123";
};
}]);
The template could be something like:
<button ng-click="button">CHANGE</button>
How can I assign values to main page from templates and show them?
You need to beware which controller you set, the names have to match. Also beware of typos, even when typing fast ;). Also look into the function call. You forgot to use () at the end. And naming things a little bit better would be recommended to (I don't say my namings are the best, but calling a function button is not very readable).
HTML
<body ng-controller="MainCtrl">
<p>Value {{value}}!</p>
<button ng-click="btnPressed()">Change</button>
</body>
JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.value = "456";
$scope.btnPressed = function() {
$scope.value = 123;
}
});
The controllers name in this example is MainCtrl. You need to refer the correct name as well in your HTML (you mix mycontroller and ProductController).
Working Plnkr
http://plnkr.co/edit/tpl:8rFfZljYNl3z1A4LKSL2
You have defined $scope.button in ProductController which set $scope.value.
But this $scope.value is come under scope of ProductController and not available under scope of mycontroller which parent scope.Thats why you getting null value.
Define $scope.value and $scope.button in mycontroller.
Or better way is define this functionality in some factory and access it wherever needed.
Or define that function and variable in $rootScope like
$rootScope.value;
but it make this global.
or define like this
$scope.$parent.value;
Inline in AngularJs is there a way to check if something is an array?
I would have thought this to work:
<div ng-show="Array.isArray(textStuff[0][1])">Hi</div>
I have verified it is in fact an array. Is there something I am missing or another way?
You can put angular.isArray on the scope...
$scope.isArray = angular.isArray;
<div ng-show="isArray(textStuff[0][1])">Hi</div>
Fiddle
You can create global filters to use in your JS or HTML to check against object types. This way you don't pollute your $rootScope or $scopes to use it everywhere, unlike the accepted answer... Angular also has some built in utility functions that can check object types:
angular
.module("yourModule")
.filter("isArray", function() {
return function(input) {
return angular.isArray(input);
};
});
In HTML:
<div ng-show="{{ textStuff[0][1]) | isArray }}">Hi</div>
You may also inject the $filter service into your Controller to access the custom filter by name and compute the filtered results when your controller instance is instantiated (and also when your data changes). This prevents performance issues due to the view expression getting computed rapidly.
angular
.module("yourModule")
.controller("MyController", MyController);
MyController.$inject = ["$filter", "$scope"];
function MyController($filter, $scope) {
this.testStuff = []; // your data
this.filteredResult = $filter("isArray")(this.testStuff[0][1]);
// or if you need to watch for data changes
var vm = this;
$scope.$watchCollection(
function() { return vm.testStuff },
function(newTestStuff) {
vm.filteredResult = $filter("isArray")(newTestStuff[0][1]);
}
);
}
<div ng-controller="MyController as my">
<div ng-show="my.filterResult">Hi</div>
</div>
I would separate logic from the view. Add state in scope and then check it
$scope.showHi = angular.isArray(textStuff[0][1]);
In view
<div ng-show="showHi">Hi</div>
UPDATE: angular 1.3.0-rc4 removed $scope.this see commit
Each instance of a $scope has a property named this that points back to itself.
Currently (1.2.0rc1) it's not prefixed with $(public/protected) or $$(internal) so it doesn't hint that it's an angular specific property.
What is the use case for it?
This question had me grepping all through the codebase for an explanation; I finally got a hint from an old test.
Since AngularJS expressions are evaluated in the context of a scope, the scope needs to have a property called this that refers to itself so that expressions that contain this work. Take the following example:
<div ng-controller="FirstController">
`this.num` (with normal scope): {{this.num}}
</div>
<div ng-controller="SecondController">
`this.num` (with scope.this removed): {{this.num}}
</div>
app = angular.module('myApp', []);
app.controller('FirstController', function($scope) {
$scope.num = 10;
});
app.controller('SecondController', function($scope) {
delete $scope['this'];
$scope.num = 10;
});
The second example does not work; see http://jsfiddle.net/BinaryMuse/mzbpz/ for a demonstration.
in my app I have a wrapper controller that handles some properties dynamically based on other-controllers within it. everything works like a charm if the other-controllers are present/static on load, but as soon as I'm trying to make them dynamic, they stop working.
It was my understanding that the $rootScope is available from everywhere within the app, is that not true?
my JS looks like this:
var webApp = angular.module("webApp",[]);
webApp.controller("ControllerA", function($scope, $rootScope){
$rootScope.cnt = 0;
$rootScope.cntPlusPlus = function(){
$rootScope.cnt++;
};
$rootScope.controllerBs = [];
var template = $(".controller-b").html();
$scope.addControllerB = function(){
$rootScope.controllerBs.push(template);
};
});
webApp.controller("ControllerB", function($scope, $rootScope){
$scope.cntPlusPlus = function(){
console.log("overwrite plus plus");
}
});
Full example: http://plnkr.co/edit/tAcv1F9y7t9q9XsQ1EFL?p=preview
I know that this would be probably better with directives, but is there any way to make it work with Controllers?
thanks for the help
Don't try to access the DOM from controller code. Never. It is very bad practice which breaks AngularJS conventions and eventually provides you with bad architecture. This also means you should not create any DOM elements manually from a controller.
Better to manipulate with the scope itself, not with its visual representation. You can add new models to scope on your button's click, which will be translated to new elements by ng-repeat directive, each with its own controller (remember controllers are instances, not singletons, so that they have separated life cycles).
You might want to make use of <script type="text/ng-template"> and ng-include here instead of hidden divs.
Try to avoid using $rootScope when possible - it is global state which can be dangerous.
It might look like this then (plunker):
HTML:
<div class="controller-a" ng-controller="ControllerA">
Controller A
<div>
<button ng-click="cntPlusPlus()">cnt++</button> CNT: {{cnt}}
</div>
<button ng-click="addB()">Add B</button>
<div ng-repeat="B in Bs">
<div ng-include="'b-template'"></div>
</div>
</div>
<script type="text/ng-template" id="b-template">
<div ng-controller="ControllerB">this is controller b: <button ng-click="cntPlusPlus()">cnt++</button></div>
</script>
JS:
var webApp = angular.module("webApp",[]);
webApp.controller("ControllerA", function($scope){
$scope.cnt = 0;
$scope.cntPlusPlus = function(){
$scope.cnt++;
};
$scope.Bs = [];
$scope.addB = function(){
$scope.Bs.push({});
};
});
webApp.controller("ControllerB", function($scope){
$scope.cntPlusPlus = function(){
console.log("overwrite plus plus");
$scope.$parent.$parent.$parent.cnt++; //should be moved to service
}
});
</script>