2016-09-15 2 views
3

Привет Я создал модель с именем billerModel и маршрут, который имеет решение с переменной биллеров. Теперь я хочу получить и назначить эту переменную внутри моего контроллера, но я получаю эту ошибку поставщика неизвестного поставщика. Ниже мой код для маршрута:Получить переменную разрешения и перейти к контроллеру

app.config(["$routeProvider", "$httpProvider",'$locationProvider',function($routeProvider, $httpProvider, $locationProvider) { 

$routeProvider 
    .when("/billers", { 
     templateUrl: 'admin/billers/index.html', 
     controller: 'billerController', 
     resolve: { 
      billerData: function(billerModel) { 
       return billerModel.getData(); 
      } 
     } 
    }); 

Ниже мой код модели

app.factory('billerModel', ['$http', '$cookies', function($http, $cookies) { 
    return { 
     getData: function() { 
     return $http({ 
      method: 'GET', 
      url: 'billers' 
     }); 
     } 
    } 
}]); 

Ниже мой код контроллера, который дает мне ошибку

app.controller('billerController', ['$scope', 'billerData', 
    function($scope, billerData){ 
     $scope.billers = billerData; 

}]); 

Я также пытался удалите ng-контроллер из моего представления, но если я это сделаю, я получу ошибку неизвестной переменной

<div style="text-align: left;" ng-controller="billerController"> 
    {{ billers }} 
</div> 

enter image description here

Ниже jsfiddle, но я не знаком о том, как использовать его, но основная структура включена здесь https://jsfiddle.net/bd06cctd/1/

+0

создается завод 'billerModel'. Но попробуйте ввести в контроллер 'billerData'. Измените ввод в 'billerModel'. –

ответ

2

Решить данные в блоках .when только для инъекций в контроллеры, определенные блоком .when. Контроллеры, введенные директивой ng-controller, не могут вводить данные разрешения.

Кроме того, если Вы вводите billerController в .when блоке и с ng-controller директивы в шаблоне .when блока, то контроллер будет инстанцирован дважды.

$routeProvider также разрешает данные, доступные в области обзора на объекте $resolve. Это могут использовать дочерние контроллеры, созданные в соответствии с директивой ng-controller.

app.controller('childController', ['$scope', 
    function($scope){ 
     $scope.billers = $scope.$resolve.billerData; 
}]); 

Контроллеров воплощенных в ng-controller директиве будут найти $resolve свойства по прототипу наследования от объема просмотра.

От Docs:

  • resolve - {Object.<string, Function>=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired. For easier access to the resolved dependencies from the template, the resolve map will be available on the scope of the route, under $resolve (by default) or a custom name specified by the resolveAs property.

- AngularJS $routeProvider API Reference

+0

Вы - спасатель жизни, который объясняет это четко. Большое спасибо –

-1

могли бы попытаться изменить:

app.factory('billerModel', ['$http', '$cookies', function($http, $cookies) { 
return { 
    getData: function() { 
    return $http({ 
     method: 'GET', 
     url: 'billers' 
    }); 
    } 
} 
}]); 

в

app.factory('billerModel', ['$http', '$cookies', function($http, $cookies) { 
    return { 
     getData: $http({ 
      method: 'GET', 
      url: 'billers' 
     }); 
    } 
}]); 

Вы возвращаетесь ano nymous, а не Promise

+0

Не повезло по этой же проблеме. –

+0

Не могли бы вы создать JSFiddle? – nikjohn

+0

Вот скрипка https://jsfiddle.net/madzmar25/bd06cctd/14/ –