我在学习angular.js,并想知道什么时候应该使用app.controller(“MyCtrl”,…),当使用函数MyCtrl($ scope){…}时。
原文链接:https://www.f2er.com/angularjs/145278.html我看到在这个例子中的两种方法没有大的区别(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; } }