javascript - Angular JS Controller 功能未进入

标签 javascript angularjs

我试图简单地通过 GET 调用将一些 JSON 数据扔到页面上。

这是我的 HTML(请注意,它已加载到具有正确 Angular 符号的 index.html 中):

<h1>Downloads</h1>
<div class="container" ng-controller="DownloadCtrl as download">
  <p>{{download.routes}}</p>
</div>

这是下载 Controller :

(function(){
  'use strict';

  angular.module('dashboardApp').controller('DownloadCtrl', DownloadCtrl);
  DownloadCtrl.$inject= ['DownloadService'];

  function DownloadCtrl(DownloadService){
    var self = this;
    self.routes = function(){
      DownloadService.getRoutes()
        .then(function(responseData) {
          self.routes = responseData;           
      });
    };
  };
})();

这是下载服务:

(function(){
  'use strict';

  angular.module('dashboardApp')
    .factory('DownloadService', DownloadService);

  DownloadService.$inject = ['$http', '$sessionStorage'];

  var baseURL = 'http://localhost:8080/Dashboard/rest/download/';

  function DownloadService ($http, $sessionStorage){
    var service = {};
    service.getRoutes = getRoutes;
    return service;

    function getRoutes(){
      return $http.get(baseURL+"route",$sessionStorage.sessionData.sessionID);
    }
  }
})();

我已经调试了该应用程序,它确实命中了self.routes,但它只是跳过了它并且没有显示任何数据。

我在控制台中也没有收到任何错误。它只是跳过该函数。

这是我的第一个 AngularJS 应用程序。

最佳答案

你的代码组织不好, 错误驻留在 View 中,因为它没有调用方法 self.routes,它只是打印出来...

你的 View 必须做类似的事情:

<p>{{download.routes()}}</p>

但是,这是一种糟糕的编码方式...... 请考虑做这样的事情:

DownloadService
  .getRoutes()
  .then(function(responseData){
    self.routes = responseData;         
  })
;

// instead of

self.routes = function(){

  DownloadService.getRoutes()
  .then(function(responseData){
    self.routes = responseData;         
  });

};

关于javascript - Angular JS Controller 功能未进入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34227142/

相关文章:

javascript - 没有回调函数的 SetTimeout() 调用会出现意外的行为

javascript - 如何在 AngularJs ng-repeat 中按数组过滤?

javascript - react 路由器用作 <Routes> 元素错误的子元素

angularjs - AngularJs 应用程序的音频播放器

javascript - 在 ng-repeat 中显示/隐藏项目

javascript - .append 不替换相似元素

javascript - 基本形式 - Javascript 代码不起作用

service - AngularJS 中的非单例服务

javascript - 如何在 Jasmine + Angular 中测试与指令的isolateScope的双向绑定(bind)?

javascript - 使用 NgTable 过滤选择