在angular 1.X中,我们可以像下面这样定义作用域函数,想知道在作用域中定义函数的最佳实践是什么。请帮助我理解以下方法中的任何一种比其他方法更受欢迎!
// first approach
angular.controller("MyController", function() {
$scope.firstFun = function() {
// do something here
};
});
// second approach
var firstFun = function($scope) {
return function() {
//use scope here and declare logic also
};
};
angular.controller("MyController", function() {
$scope.firstFun = firstFun($scope);
});发布于 2017-06-21 03:51:06
在我看来,有一种比你列出的两种更好的方法,它是这样的:
(function (angular) {
"use strict";
angular.module("YourModule")
.controller("MyController", MyController);
function MyController() {
var ctrl = this;
// All controller functions and variables bindings
// will be listed below, in alphabetic order
ctrl.firstFun = firstFun;
ctrl.myName = "name";
function firstFun() {
}
}
}(angular));我不认为简短的代码是写得很好的代码。所以如果我是你,我会试一试John Papa's Style Guide。
发布于 2017-06-21 01:01:41
我个人更喜欢声明函数的第一种方法。使用一种方法比使用另一种方法没有额外的好处。实际上,在第二种方法中,你必须写几行额外的代码。您可以遵循任何您认为更方便使用的方法。
https://stackoverflow.com/questions/44658671
复制相似问题