无法绑定 $scope 值以查看 Url 更改 [英] Unable to bind $scope value to view on Url change
问题描述
我尝试使用 angularJS 创建一个搜索应用程序.当路由器 Url 更改时,我遇到了绑定 $scope 值以查看的问题.
I trying to create a search application using angularJS.I am facing the issue in binding $scope values to view when router Url changes.
我在/main 中有一个搜索字段.当我编写查询并单击搜索按钮时,该函数会获取数据并分配给范围变量.路由器 URL 将更改为/结果"和相应的视图显示.但视图没有绑定范围值./main 和/Result 使用相同的控制器.
I have a search field in /main.When I write the query and click on search button, the function does the data fetch and assign to a scope variable.The router URL will change to '/Result' and the respective view is displayed.But the view doesn't have the scope values bound. /main and /Result uses the same controller.
主模块中的路由器代码:
router code in main module :
$routeProvider.
when('/main', {
templateUrl: '/views/search.html',
controller: 'searchCtrl'
}).when('/Result',{
templateUrl:'/views/Result.html',
controller: 'searchCtrl' ,
reloadOnSearch: false
}).otherwise({
redirectTo: '/main'
});
控制器:从/main 按钮点击
$scope.fetchResult=function(searchWord){
shService.fetchResultDocumentsList(searchWord).data.then(function(response){
//service call here-data fetch is successfull.
$scope.docResultList=response[0];
$scope.docResultList=response[0];
$scope.documents = $scope.docResultList.data.documentEntities;
$location.path('/Result');
}
当相应的视图发生变化时,绑定没有完成.但是当我用 $rootScope.documents 替换 $scope.documents 时绑定成功.我读过 $scope 被鼓励使用 $rootScope.
When the respective view is changing, the binding is not done.But when i replace the $scope.documents with $rootScope.documents binding is successful. I have read the use of $scope is encouraged over $rootScope.
推荐答案
当您从一页移动到另一页时,控制器和 $scope
会重新初始化.如果您想使用 $scope ,您应该考虑使用 service
在控制器之间共享数据.
The controller and $scope
gets re initialized when you move from one page to another page. if you want to use $scope , you should consider using service
to share the data across controllers.
创建一个服务,它将保存您的变量.
Create a service, that will hold your variable.
angular.service("dataService", function() {
this.value1 = ""
});
在您的控制器中引用该服务,
reference that service in your controllers,
angular.controller("myCntrl1", function($scope, dataService) {
$scope.val= dataService.value1 ;
});
angular.controller("myCntrl2", function($scope, dataService) {
$scope.val= dataService.value1 ;
});
这篇关于无法绑定 $scope 值以查看 Url 更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!