Angular's “controllerAs” not working in routeProvider

后端 未结 4 1295
醉话见心
醉话见心 2021-02-08 17:50

I am trying to use the controllerAs property on a $routeProvider route without any success.

Here is the sample code:

var app =          


        
4条回答
  •  后悔当初
    2021-02-08 18:19

    To be clear--because I don't think the accepted answer was explicit--the problem with your example is that even though you are assigning a value to controllerAs you are bypassing it by still using $scope.

    The "vm" approach stands for view-model which is just a convention, but IMO is far more representative of what is actually going on than "$scope". All we're really trying to do here is bind the view to the view model.

    That being said you can technically use both controllerAs AND normal $scope at the same time plunk.

    Additionally, the difference between Rohan's examples A and B is that A is the way you should be doing it because you are able to leverage JavaScript's prototypal inheritance which is conducive to better perf. It's also worth noting that because you are now using controllerAs and this you no longer need to inject $scope.

    // Functioning Example    
    var app = angular.module('app', ['ngRoute']);
    
    app.config(['$routeProvider', '$locationProvider',
      function($routeProvider) {
      $routeProvider
        .when('/', {
          template:'
    This should be visible:{{ vm.one }}
    This should not:{{ one }}
    ', controller: 'Ctrl', controllerAs: 'vm', }); }]); app.controller('Ctrl', function() { this.one = 'actual'; });

提交回复
热议问题