有意见的Javascript,传递解析器无法正常工作(ui-router)

时间:2014-11-12 21:41:48

标签: javascript angularjs angular-ui-router

简单来说,我正在调整一个简单的例子,以opinionated javascript produced by Todd Motto进行练习。

Plunkr Of Issue 如前所述

Plunkr Of using a Resolver 使用传统的解析器

问题是我的解析器无法访问工厂查询结果。我不知道为什么,但我发现这样做的方法太过于苛刻。在这里传递已解析对象的最佳方法是什么?

在这个例子中,我有一个简单的MVVM页面,其中包含一个带有controllerAs语法的div。

<div ng-controller="ProjectCtrl as vm">
    <h1>Hello: {{vm.message}}</h1>
</div>

这是自以为是的javascript的配置。

'use strict';

(function(){
  /* Module & Dependencies */
  angular.module('project', ['ui.router']);
  angular.module('project').factory('Project', Project);
  angular.module('project').controller('ProjectCtrl', ProjectCtrl);
  angular.module('project').config(ProjectStates);


  /* Factory */
  function Project($resource){
    return $resource('app/rest/projects/:id', {}, {
      'query': { method: 'GET', isArray: true},
      'get': { method: 'GET'}
    });
  };

  /* Controller */
  function ProjectCtrl(Project){
    var model = this;
    /* No access to anything that's resolved */

    model.message = "World";
  };

  ProjectCtrl.resolve = {
    projectResolver: function(Project, $q){
      return Project.query();
    }
  }


  /* Routes */
  function ProjectStates($stateProvider, $urlRouterProvider, $translateProvider, USER_ROLES) {
    /* Default state and parent to all project states */
    $stateProvider.state('project',{
      url: "/project",
      templateUrl: "views/projects.html",
      resolve: ProjectCtrl.resolve
    });    
  };


})();

1 个答案:

答案 0 :(得分:1)

您可以通过依赖注入

使用查询结果
function ProjectCtrl(Project, projectResolver){
  var model = this;

  // now use your queried result, e.g.
  model.projects = projectResolver;

  model.message = "World";
};

但这仅在您在状态对象中定义控制器和controllerAs属性时才有效:

$stateProvider.state('project',{
  url: "/project",
  templateUrl: "views/projects.html",
  resolve: ProjectCtrl.resolve,
  controller: "ProjectCtrl",
  controllerAs: "vm"                                                  
});

现在 Html 应如下所示:

...
<body>
    <ui-view>
</body>
...

views / projects.html 文件可能如下所示:

<h1>Hello {{vm.message}}!</h1>
<ul><li ng-repeat='project in vm.projects' ng-bind='project.name'></li></ul>


这是 working demo