【问题标题】:AngularJS view not rendered with data received in a service using routeparamsAngularJS 视图未使用路由参数在服务中接收到的数据呈现
【发布时间】:2014-10-18 04:22:20
【问题描述】:

当我在我的 searchTrails.html 上单击此链接时,我试图在 trailDetails.html 上显示单个跟踪信息。 trailDetails.html 上没有任何内容。但是,如果我将 getDataService.js 中的代码移动到 searchTrailsController.js,一切都会好起来的。我不明白为什么。有人可以提出一些建议吗?

app.js:

var app = angular.module("crowd", ["ngRoute"]);
app.config(function ($routeProvider){
    $routeProvider.when("/",{
        templateUrl:"views/searchTrails.html",
        controller:"searchTrailsCtrl"
    });
    $routeProvider.when("/trails/:trailId", {
        templateUrl: "views/trailDetails.html",
        controller: "searchTrailsCtrl"
    });
})

getDataService.js:

app.service("dataService", function ($http, $routeParams){
this.getSingleTrail = function (){
    var trail = [];
    $http.get("http://localhost:8080/DMW-skeleton-1.0/trail/findTrailByTrailId/" + $routeParams.trailId)
    .success(function (data){
        trail.push(data);
    })
    return trail
}})

searchTrailsController.js:

app.controller("searchTrailsCtrl", function ($scope, dataService ) {
$scope.trail = dataService.getSingleTrail();})

但是 trailDetails.html 中什么都没有:

<p>{{trail.trailInfo.trailDescription}}</p>

【问题讨论】:

    标签: angularjs angularjs-service angularjs-routing


    【解决方案1】:

    问题是您的数据是异步传入的,但您尝试同步保存它们。 一步一步:

    1. 你定义变量 trail = []
    2. 您将跟踪变量返回给控制器
    3. 服务器响应数据(但您已经返回线索)

    你可以使用下一个代码解决这个问题:

    app.service("dataService", function ($http, $routeParams){
    this.getSingleTrail = function (){
        var trail = [];
        return $http.get("http://localhost:8080/DMW-skeleton-1.0/trail/findTrailByTrailId/" + $routeParams.trailId);
    }})
    
    
    app.controller("searchTrailsCtrl", function ($scope, dataService ) {
        $scope.trail;
      dataService.getSingleTrail().success(function(data){
        $scope.trail = data;
      });
    })
    

    【讨论】:

    • 谢谢!这对我来说非常有效。这意味着将数据放入变量必须在 controller.js 中编写。而 service.js 只是用来放 URL 的?请原谅我是 AngularJS 的新手。我曾经把那些获取数据的代码放在 controller.js 中。但是我想在不同的控制器之间共享一些数据,所以我开始使用服务。
    • 也就是说我可以在service.js中写this.trail = data
    猜你喜欢
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    • 2021-05-29
    • 2017-11-09
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多