我想在提交表单时使用$ http.get方法。 这是我的代码。调用方法时会设置对象$ scope.questions,但数据不会显示在div中。而且,当$ http.get方法在signIn()函数之外时,它可以正常工作。
$scope.signIn = function(data) {
$location.path('/profile');
var url = "database/fetch_data.php?query=";
var query = "Select * from question where userId=2";
url += query;
$http.get(url).success(function(questionData) {
$scope.questions = questionData;
console.log($scope.questions);
});
};
<div>
User Profile
<br/>Question Posted
<br/>
<input ng-model="query.title" id="value" type="text" placeholder="Search by Title..." ">
<div>
<ul>
<li ng-repeat="question in questions | filter: query ">
{{question.title}}
</li>
</ul>
</div>
<br/>
</div>
答案 0 :(得分:0)
您需要在http请求中移动$location.path('/profile')
。请记住,http请求是异步调用。您应该在获取数据之后重定向。
$scope.signIn = function(data) {
var url = "database/fetch_data.php?query=";
var query = "Select * from question where userId=2";
url += query;
$http.get(url).success(function(questionData) {
$scope.questions = questionData;
console.log($scope.questions);
$location.path('/profile');
});
};
答案 1 :(得分:0)
如果您要重定向到具有完全独立范围的其他路线,您将失去在成功处理中设置的任何范围。
从我正在阅读的内容中,您可以点击按钮进行操作。在该操作之后,您将使用单独的控制器重定向到另一个页面并尝试保留数据。
不幸的是,Angular还没有找到一个很好的方法来做到这一点。通过控制器和范围持久保存数据的最简单方法是创建一个服务,将其存储在一个控制器中并在另一个控制器中获取。
例如:
$scope.signIn = function(data) {
var url = "database/fetch_data.php?query=";
var query = "Select * from question where userId=2";
url += query;
$http.get(url).success(function(questionData) {
$location.path('/profile');
storageService.store("question", questiondata)
});
};
您的新工厂要通过以下方式保留数据:
angular.module('moduleName').factory('storageService', [
function () {
return {
store: function (key, value) {
localStorage.setItem(key, JSON.stringify(value));
},
get: function(key) {
return JSON.parse(localStorage.getItem(key));
},
remove: function(key) {
localStorage.removeItem(key);
}
}
}
]);
访问数据的其他控制器:
$scope.question = storageService.get("question");
// remove localstorage after you've grabbed it in the new controller
storageService.remove("question");
做一些有点“hacky”的替代方案。使用localStorage通过控制器保存数据的方法是使用ui-router并对你重定向到的路由有一个解决方法。
例如:
$scope.signIn = function(data) {
$state.go('profile');
};
在你的路线档案中:
.state('profile', {
url: '/profile'
controller: profileControllerName,
templateUrl: 'profileHtmlTemplate.html',
resolve: {
'questions': [function() {
var url = "database/fetch_data.php?query=";
var query = "Select * from question where userId=2";
url += query;
$http.get(url).success(function(res) {
return res.data;
});
}]
}
}
在个人资料控制器中:
提出您的问题&#39;解析到你的控制器并分配`$ scope.question = questions;
这将在您单击路由后立即进行HTTP调用,如果成功则返回数据,然后呈现页面。如果解析没有返回成功,它将不呈现页面。这将确保在加载依赖于该数据的页面之前加载您的数据。
我强烈建议您使用服务来保存针对应用程序特定部分的HTTP调用。如果你有一个GET问题,POST问题,PUT问题。我会创建一个questionService并在那里制作我所有的HTTP方法,这样你就不必弄乱你的路线了。你只需要打电话:
.state('profile', {
url: '/profile'
controller: profileControllerName,
templateUrl: 'profileHtmlTemplate.html',
resolve: {
'questions': [function() {
return questionService.getQuestions(id).then(function(res) {
return res.data;
})
}]
}
}