2015-07-14 3 views
0

Это будет звучать странно, но у меня есть этот сервис:AngularJs ControllerAs не работает, как я ожидал

.factory('ListControllerService', function() { 

    // Default constructor expecting a service 
    return function (service) { 

     // Define this 
     var self = this; 

     // Define our list 
     self.list = []; 

     // Create our page sizes array 
     self.pageSizes = [10, 20, 50, 100]; 

     // For filtering and sorting the table 
     self.pageSize = self.pageSizes[0]; 
     self.predicate = 'name'; 
     self.reverse = false; 
     self.filter = ''; 

     // For deleting 
     self.delete = function (e, model) { 

      // Delete the item 
      service.delete(model.id); 
     }; 
    }; 
}) 

, который вводится в мой контроллер:

.controller('DashboardController', ['ListControllerService', 'CenterService', 'companyId', 'centers', function (Controller, service, companyId, centers) { 

    // Assign this to a variable 
    var self = new Controller(service); 

    // Assign our centers 
    self.list = centers; 
}]) 

Мой маршрут настроен как это:

$stateProvider.state('dashboard', { 
    url: '/dashboard', 
    templateUrl: '/assets/tpl/dashboard.html', 
    controller: 'DashboardController', 
    controllerAs: 'controller', 
    resolve: { 

     companyId: ['$rootScope', '$state', function ($rootScope, $state) { 

      // Get our current user 
      var user = $rootScope.user; 

      // If we don't have a company id, redirect to the login screen 
      if (!user.companyId) { 

       // Redirect to the login page 
       $state.go('/account/login'); 
      } 

      // Return our companyId 
      return user.companyId; 
     }], 

     // Resolve our centers before the state loads 
     centers: ['$rootScope', '$state', 'CenterService', 'toastr', function ($rootScope, $state, service, toastr) { 

      var centers; 

      // Get our current user 
      var user = $rootScope.user; 

      // if we are an administrator 
      if (user.role.toLowerCase() === 'administrator') { 

       // Get all centers 
       centers = service.all(); 
      } else if (user.role.toLowerCase() === 'superuser') { 

       // Get the company centers 
       centers = service.company(user.companyId); 
      } else { 

       // Get our user centers 
       centers = service.user(user.id); 

       // If we get our centers 
       centers.then(function (response) { 

        // Count our results 
        var count = response.data.length; 

        // If we have only 1 result 
        if (count === 1) { 

         // Get our center 
         var center = response.data[0]; 

         // Redirect to our collections 
         $state.go('collections', { centerId: center.id }); 
        } 

       // If there is an error 
       }, function() { 

        // Tell the user there was an error 
        toastr.error('Failed to retrieve your center(s).'); 
       }); 
      } 

      // Return our centers 
      return centers; 
     }] 
    }, 
    data: { 
     requireLogin: true, 
     pageTitle: 'Dashboard' 
    } 
}) 

Как вы можете видеть, что я установить controllerAs недвижимость, так что я бы ожидать, что на мой взгляд, я просто не могу сделать нг-повтора в списке, как это:

<tr ng-repeat="center in controller.list.data"> 
    <td> 
     {{ center.name }} 
    </td> 
</tr> 

, но ничего не происходит. Если я изменить мой контроллер к этому:

.controller('DashboardController', ['ListControllerService', 'CenterService', 'companyId', 'centers', function (Controller, service, companyId, centers) { 

    // Assign this to a variable 
    var self = this; 

    // Assign our centers 
    self.list = centers; 
}]) 

он работает отлично. Может кто-нибудь сказать мне, почему?

+0

довольно простой ... нет ссылки на 'this' в контроллере – charlietfl

ответ

0

controllerAs означает, что экземпляр контроллер публикуется на сферу под «псевдонимом», так что, в вашем случае, под $scope["controller"] поскольку "controller" это псевдоним.

Экземпляр контроллер ссылается this внутри функции контроллера:

.controller("DashboardController", function(){ 

    this.foo = "foo"; 

    var self = this; // now self also references the controller instance 
    self.bar = "bar"; 
}); 

Тогда вы можете получить свойства экземпляра в HTML:

<div ng-controller="DashboardController as controller"> 
    <div>{{controller.foo}} will be "foo"</div> 
    <div>{{controller.bar}} will be "bar"</div> 
</div> 

И это то, что вы сделали во втором дело.

В первом случае self относится к чему-то еще, но не экземпляр контроллера, и поэтому вы не имеете .list как свойство экземпляра контроллера, и, таким образом, undefined в этом выражении:

<tr ng-repeat="center in controller.list.data"> 
+0

как я могу заставить мой работать, чтобы все свойства/функции ListControllerService были доступны контроллеру? – r3plica

Смежные вопросы