Angular.js “Controller as …” + $scope.$on

前端 未结 3 950
滥情空心
滥情空心 2021-01-17 10:42

If i\'d like to use the \"Controller as ...\" syntax in Angular, how should I approach things like $scope.$on(...) that i need to put inside the controller?

I get a

相关标签:
3条回答
  • 2021-01-17 10:55

    Inject $scope and your controller is accessible by whatever you named it

    EG:

    $stateProvider
      .state('my-state', {
        ...
        controller: 'MyCtrl',
        controllerAs: 'ctrl',
        ...
      });
    
    
    
    .controller('MyCtrl', function($scope) {
      var $this = this;
      $scope.$on('ctrl.data', function(new, old) {
        // whatevs
      });
      $timeout(function() {
        $this.data = 'changed';
      }, 1000);
    });
    
    0 讨论(0)
  • 2021-01-17 11:08

    As far as I know, you need to inject $scope if you want $scope watchers/methods. ControllerAs is just syntactic sugar to enable to see more clearly the structure of your nested controllers.

    Three ideas though which may simplify your code.

    1. Use var vm = this, in order to get rid of the bind(this).

      var vm = this;
      vm.whereAmINow = "/";
      
      $scope.$on('$locationChangeStart', function(event) {
          vm.whereAmINow = $location.path();
      });
      
      vm.jumpTo = function(where) {
          $location.path(where);
      }
      
    2. The whole whereamINow variable makes sense putting it into the initialization of app aka .run() (before config) since I assume it's a global variable and you don't need to use a $scope watcher/method for it.

    3. Another option is to use a factory to make the changes persist, so you simply create a location factory which holds the current active path.

    0 讨论(0)
  • 2021-01-17 11:13

    Ok, i think people just do the same, just as in this question:

    Replace $scope with "'controller' as" syntax

    0 讨论(0)
提交回复
热议问题