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

前端 未结 3 983
滥情空心
滥情空心 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 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.

提交回复
热议问题