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

HTML/ビューからアクセスできるのは、$scope オブジェクトで定義されたメソッドだけです。ng-click、filters などの例 -メソッドに html からアクセスする必要がない場合は、$scope にバインドする必要はありません。

于 2015-10-28T11:07:03.273 に答える
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 に答える