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; } }
Advertisements. AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is defined using ng-controller directive. A controller is a JavaScript object that contains attributes/properties, and functions.
A controller is usually used to contain and maintain the logic for your view, which gets bound to your view via $scope. A directive is something that you might use repeatedly and is called in your view directly through the directive name which you can pass in as an attribute.
The controller in AngularJS is a JavaScript function that maintains the application data and behavior using $scope object. You can attach properties and methods to the $scope object inside a controller function, which in turn will add/update the data and attach behaviours to HTML elements.
A controller is a function you write to control your data. With a self-written controller, you can modify data anyway you want: Convert to upper case.
The major reasons for using the module based controller declaration are
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With