angularjs – app.controller vs angular.js中的函数
发布时间:2020-12-17 08:29:10 所属栏目:安全 来源:网络整理
导读:我在学习angular.js,并想知道什么时候应该使用app.controller(“MyCtrl”,…),当使用函数MyCtrl($ scope){…}时。 我看到在这个例子中的两种方法没有大的区别(link to a plunker): index.html: body ng-app="myApp" div ng-controller="FirstCtrl as ap
我在学习angular.js,并想知道什么时候应该使用app.controller(“MyCtrl”,…),当使用函数MyCtrl($ scope){…}时。
我看到在这个例子中的两种方法没有大的区别(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; } }
在你的两个用法中,推荐的方法是注入$ scope并使用它(而不是使用这个,你可以在第二种方法中做)。
方法一和方法二的区别在于如何支持缩小。在前者中,你可以提供一个注入的参数数组,而在后者中你可以修改$ inject。这当然有点技术,但强烈建议支持缩小。请参阅文档中的A note on minification。 前者也没有在全局范围中命名函数,这通常是一件好事! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |