我有一个包含ng-view的页面。此嵌入模板是一个表,当单击一行时切换到该行的详细信息模板。我一直无法让控制器收集细节'数据并成功显示它。
使用下面的代码,数据将通过$ http.get和'详细信息收集。显示视图,但数据未绑定到'详细信息'图。
有人可以解释我在哪里出错吗?
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.
});
};
} )
})();
答案 0 :(得分:1)
不会在视图中保留。一旦视图消失,视图的$ scope上的所有数据也将被清除。您需要做的是将数据保存在Factory中。
看看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>