如果在路线中指定了搜索字词,我想在页面加载时提交搜索表单。问题是searchForm
运行时尚未定义search()
。我已经看到其他人通过将ng-controller放在表单元素上来实现这一点,但是我在这个页面上有多个表单,所以控制器必须是表单的父表。
当我调用search()时,如何确保定义表单?
myModule.controller('MyController', ['$scope', '$routeParams',
function($scope, $routeParams){
$scope.model = {searchTerms: ""};
$scope.search = function(){
if($scope.searchForm.$valid){
...
}
};
if($routeParams.terms !=""){
$scope.model.searchTerms = $routeParams.terms;
$scope.search();
}
}]);
查看:
<div ng-controller="MyController">
<form name="searchForm" ng-submit="search()">
...
</form>
<form name="detailForm" ng-submit="save()">
...
</form>
</div>
答案 0 :(得分:2)
这似乎有效:
$scope.$on('$routeChangeSuccess', function () {
if($routeParams.terms !=""){
$scope.model.searchTerms = $routeParams.terms;
$scope.search();
}
});
答案 1 :(得分:1)
您是否尝试在searchForm上使用$watch
?
if($routeParams.terms != "") {
var unregister = $scope.$watch(function() {
return $scope.searchForm;
}, function() {
// might want to wrap this an if-statement so you can wait until the proper change.
unregister(); //stop watching
$scope.model.searchTerms = $routeParams.terms;
$scope.search();
});
}