我有以下 AngularJS 应用程序,由一个模板 (index.html
)、一个应用程序定义 (app.js
)、一个 Controller 定义 (controllers .js
) 和托管页面 (host.jsp
)。
代码如下:
搜索.jsp
<div class="container-fluid" ng-app="facetedSearch">
<div class="row-fluid" ng-view>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script src="/resources/js/page/search/app.js"></script>
<script src="/resources/js/page/search/controllers.js"></script>
应用程序.js
angular.module('MyApp', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {templateUrl:'/index.html', controller: MyController}).
otherwise({redirectTo: '/'});
}]);
Controller .js
var MyController=['$scope','$http','$location',function ($scope, $http, $location) {
//do some fancy stuff
if($scope.myAttribute===undefined){
$scope.myAttribute=someDataFromHttpRequest;
}
$location.search(someParameters);
}];
index.html 和 host.jsp 没有显示,因为简洁且无关紧要。
Controller 从 Ajax 请求中获取一些数据,将其中一些数据存储在 $scope
中以避免再次请求它,并将其显示给用户并等待输入。当用户在 View 中选择一些数据时,我更新 URL 查询部分以反射(reflect)选择更改。但我想通过检查数据是否在 $scope
中可用来避免后续的 Ajax 请求。
我面临的问题是 $scope.myAttribute
始终未定义。它会根据每个请求重置。我认为我在滥用 AngularJS。有什么线索吗?
最佳答案
当您离开 Controller 时,作用域就会被销毁。我会考虑制作一种服务来存储您想要的东西。
angular.module('MyApp', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {templateUrl:'/index.html', controller: MyController}).
otherwise({redirectTo: '/'});
}])
.service("myService", function(){
this.myAttribute = null;
});
var MyController=['$scope','$http','$location', 'myService',function ($scope, $http, $location, myService) {
//do some fancy stuff
if(myService.myAttribute===null){
myService.myAttribute=someDataFromHttpRequest;
}
$location.search(someParameters);
}];
服务用于在多个 Controller /指令之间共享日期,所以我很确定这就是您想要的。
这是关于它们的文档信息:http://docs.angularjs.org/guide/dev_guide.services.creating_services
关于javascript - 为什么我的 $scope 属性在我的 AngularJS 应用程序中不断重置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13939244/