AngularJS : 是否有必要将我所有的控制器方法绑定到 $scope
AngularJS : Is it necessary to bind all my controller methods to $scope
我们什么时候需要将方法绑定到控制器中的 $scope,我正在处理的方法只是对对象的映射操作。
Example :
$scope.myVar = {};
function myMyObject(x) {
$scope.myVar = {
"xKey":x
}
}
to
$scope.myMyObject = function(x) {
$scope.myVar = {
"xKey":x
}
}
myMyObject(10);
$scope.myMyObject(10);
Is it necessary to bind $scope to myMyObject method here ?
仅当需要从视图中调用时才将方法绑定到 $scope
。如果它们只是您仅从控制器本身调用的私有方法,则无需污染作用域。
在您的特定场景中,无需将 myMyoObject()
绑定到范围。
编辑: 您可以完全避免使用 $scope 并使用 controllerAs 语法,在这种情况下,您可以绑定到 this 而不是绑定到 $scope。非public 函数仍将不受任何约束。
只能从 HTML/view 访问在 $scope 对象上定义的方法。来自 ng-click、过滤器等的示例
-如果不需要从 html 访问您的方法,则无需将其绑定到 $scope.
作为一种好的做法,您可以在控制器中声明所有函数,然后仅将需要的函数绑定到 $scope。
示例:
function _myHelperFunction(param) {
//do some stuff
}
function myFunction(otherParam) {
//do some stuff or use the _myHelperFunction
}
function myFunction2(otherParam) {
//do some stuff or use the _myHelperFunction
}
function myFunction3(otherParam) {
//do some stuff or use the _myHelperFunction
}
$scope.myFunction = myFunction
$scope.myFunction2 = myFunction2
$scope.myFunction3 = myFunction3
使用 ES6 解构甚至更好
[$scope.myFunction, $scope.myFunction2, $scope.myFunction3] =
[myFunction, myFunction2, myFunction3]
或者:
angular.extend($scope, {
myFunction,
myFunction2,
myFunction3
})
控制器本身保持独立功能。
将所有函数添加到 $scope 将影响长 运行 和具有大型函数的复杂应用程序的应用程序性能
仅当您想在 html(view/partial) 或子 $scopes
中访问它时,才在 $scope 中写入函数
在父 $scope 中编写的函数可供子 $scopes 访问
我们什么时候需要将方法绑定到控制器中的 $scope,我正在处理的方法只是对对象的映射操作。
Example :
$scope.myVar = {};
function myMyObject(x) {
$scope.myVar = {
"xKey":x
}
}
to
$scope.myMyObject = function(x) {
$scope.myVar = {
"xKey":x
}
}
myMyObject(10);
$scope.myMyObject(10);
Is it necessary to bind $scope to myMyObject method here ?
仅当需要从视图中调用时才将方法绑定到 $scope
。如果它们只是您仅从控制器本身调用的私有方法,则无需污染作用域。
在您的特定场景中,无需将 myMyoObject()
绑定到范围。
编辑: 您可以完全避免使用 $scope 并使用 controllerAs 语法,在这种情况下,您可以绑定到 this 而不是绑定到 $scope。非public 函数仍将不受任何约束。
只能从 HTML/view 访问在 $scope 对象上定义的方法。来自 ng-click、过滤器等的示例 -如果不需要从 html 访问您的方法,则无需将其绑定到 $scope.
作为一种好的做法,您可以在控制器中声明所有函数,然后仅将需要的函数绑定到 $scope。
示例:
function _myHelperFunction(param) {
//do some stuff
}
function myFunction(otherParam) {
//do some stuff or use the _myHelperFunction
}
function myFunction2(otherParam) {
//do some stuff or use the _myHelperFunction
}
function myFunction3(otherParam) {
//do some stuff or use the _myHelperFunction
}
$scope.myFunction = myFunction
$scope.myFunction2 = myFunction2
$scope.myFunction3 = myFunction3
使用 ES6 解构甚至更好
[$scope.myFunction, $scope.myFunction2, $scope.myFunction3] =
[myFunction, myFunction2, myFunction3]
或者:
angular.extend($scope, {
myFunction,
myFunction2,
myFunction3
})
控制器本身保持独立功能。
将所有函数添加到 $scope 将影响长 运行 和具有大型函数的复杂应用程序的应用程序性能
仅当您想在 html(view/partial) 或子 $scopes
中访问它时,才在 $scope 中写入函数在父 $scope 中编写的函数可供子 $scopes 访问