AngularJS: When to pass $scope variable to function

后端 未结 6 1073
滥情空心
滥情空心 2020-12-14 01:56

I am using the TodoMVC app to get better with the AngularJS framework. In the index.html on lines 14-16 you see this:

6条回答
  •  一整个雨季
    2020-12-14 02:25

    The custom behavior methods, such as ng-click, ng-submit etc. allow us to pass parameters to methods being called. This is important since we may want to pass something that may not be available freely across till the handler in the controller. For eg,

    angular.module('TestApp')
    .controller('TestAppController', ['$scope', function($scope) {
        $scope.handler = function(idx) {
            alert('clicked ' + idx.toString());
        };
    }]);
    
    

    In case of your second example, since allChecked is within the scope of the same controller which defines markAll(), you are absolutely correct, there is no need to pass anything. We are only creating another copy.

    The method would have to simply be refactored to use whats available in the scope.

    $scope.markAll = function () {
        todos.forEach(function (todo) {
            todo.completed = $scope.allChecked;
        });
    };
    

    Hence, even though we have the option to use parameters in these methods, they are only required some of the time.

提交回复
热议问题