0

我们什么时候需要将方法绑定到控制器中的 $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 ?
4

4 回答 4

1

作为一种好的做法,您可以在控制器中声明所有函数,然后仅将您需要的函数绑定到 $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
})
于 2015-10-28T11:46:30.517 回答
1

$scope仅在需要从视图调用方法时才绑定方法。如果它们只是您仅从控制器本身调用的私有方法,则无需污染范围。

在您的特定场景中,无需绑定myMyoObject()到范围。

编辑:您可以完全避免使用 $scope 并使用 controllerAs 语法,在这种情况下,不是绑定到 $scope,而是绑定到 this。非公共功能仍然不受任何约束。

于 2015-10-28T11:04:35.430 回答
1

只有在 $scope 对象上定义的方法才能从 HTML/view 访问。来自 ng-click、过滤器等的示例 - 如果您的方法不需要从 html 访问,则无需将其绑定到 $scope。

于 2015-10-28T11:07:03.273 回答
0

保持控制器本身的独立功能。

将所有函数添加到 $scope 将影响应用程序在长期运行和具有大型函数的复杂应用程序中的性能

仅当您想在 html(view/partial) 或子 $scopes 中访问它时才在 $scope 中编写函数

子 $scopes 可以访问在父 $scope 中编写的函数

于 2015-10-29T09:57:23.747 回答