2016-01-27 65 views
0

我有一個包含ng-view的頁面。這個嵌入式模板是一個表格,當單擊一行時切換到該行的詳細模板。我一直無法讓控制器收集「細節」數據併成功顯示它。Angular:無法加載數據併成功更改視圖

通過下面的代碼,通過$ http.get收集數據,並顯示'detail'視圖,但數據未綁定到'detail'視圖。

有人可以請解釋我哪裏錯了嗎?

Controller.js

(function(){ 
    var appName = 'theApp' 
    var app = angular.module('theApp', ['ngRoute']) 
    .config(function appConfig($locationProvider, $routeProvider){ 
     $routeProvider 
     //route that is called when "Show Location" is called below. 
     .when('/' + appName + '/location/:id', { 
      controller: 'Controller', 
      templateUrl: function(params){ return appName + '/location/detail/'+params.id; } 
     }) 
     .when('/' + appName + '/location',{ 
      controller: 'Controller', 
      templateUrl: function(params){return appName + '/location/list'} 
     }) 

     $locationProvider.html5Mode(true); 
    }); 

    app.controller('Controller', function($scope, $location, $window, $http){ 
     $http.get('/Service/data/location/list').success(function(locationData) { 

      $scope.locationList = locationList; 
      $scope.locationDetail = locationDetail; 
     }); 

     $scope.showLocation = function(id){ 
      $http.get('/Service/data/locations/detail/'+id) 
       .success(function(locationDetail){ 
        //data exists here 
        $scope.locationDetail = locationDetail; 
        //data successfully updated to $scope at this point. 
        $location.url($location.path() + '/' + id); 
        //templateUrl successfully shown, but without data. 
      }); 
     }; 
    }) 
})(); 

回答

1

的角度數據不會在觀點存在。一旦視圖消失,視圖$範圍內的所有數據也將被清除。你需要做的是將數據保存在工廠中。

看看this post,它解釋瞭如何將數據從1視圖傳遞到另一個視圖。

angular 
 
    .module('app', []) 
 
    .factory('myFactory', myFactory) 
 
    .controller('myCtrl1', myCtrl1) 
 
    .controller('myCtrl2', myCtrl2); 
 

 
    function myFactory() { 
 
    var fromSender = null; 
 
    return { 
 
     setSender: function(sender) { 
 
     fromSender = sender; 
 
     }, 
 
     getSender: function() { 
 
     return fromSender; 
 
     } 
 
    }; 
 
    } 
 

 
    function myCtrl1(myFactory) { 
 
    var vm = this; 
 
    vm.setSender = myFactory.setSender; 
 
    } 
 

 
    function myCtrl2(myFactory) { 
 
    var vm = this; 
 
    vm.getSender = myFactory.getSender; 
 
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script> 
 

 
<div ng-app="app"> 
 
    <div ng-controller="myCtrl1 as ctrl1"> 
 
    Controller 1: <br> 
 
    <button ng-click="ctrl1.setSender('from controller 1')">Send to myFactory</button> 
 
    </div> 
 
    <hr> 
 
    <div ng-controller="myCtrl2 as ctrl2"> 
 
    Controller 2: <br> 
 
    value from ctrl1 via myFactory: {{ctrl2.getSender()}} 
 
    </div> 
 
</div>

+0

感謝您的解釋。 – KickinMhl