Вопрос

In my controller I have several local functions that are related to the $scope. They seem to get out of control now as that number increases. What is the proper pattern to structure these local controller functions?

For example,

function myController($scope) {
    $scope.func1 = function() {
        // do something with $scope
    }
    $scope.func2 = function() {
        // do something with $scope
    }
    $scope.func3 = function() {
        // do something with $scope
    }

    // ... controller code here ...
}

Is there a good way to make these local func1, func2, func3 more manageable?

Это было полезно?

Решение

You could define your controller as a class, and use the prototype to add functionnality :

var myController = function($scope){
  var _this = this;

  $scope.func1= function(){
    _this.func1();
  };
};

myController.prototype.func1 = function(){
  // do something here
};

app.controller('myController', myController);

This way you will avoid "scope soup". There is a great article about it here

Note that you could also avoid $scope using the "as" keyword:

<div ng-controller="myController as ctrl">
   <input ng-click="ctrl.func1()">
</div>

var myController = function(){
    this.someVar = "A value";
};
myController.prototype.func1 = function(){
   // do something here
};

Другие советы

I can share my approach:

function myController($scope) {

     $scope.func1 = func1;
     $scope.func2 = func2;


    func1 = function() {

    }
    func2 = function(x) {
        // do something with x
    }
}

And when I call func2 I give it $scope.whatever I need, that way I keep my $scope out of my func body.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top