为什么我的$ scope属性会在我的AngularJS应用程序中继续重置?

时间:2012-12-18 18:31:36

标签: javascript angularjs

我有以下AngularJS应用程序,它由模板(index.html),应用程序定义(app.js),控制器定义(controllers.js)和托管页面({{1)组成。 }})。

代码如下:

search.jsp的

host.jsp

app.js

<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>

controller.js

angular.module('MyApp', []).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
     when('/', {templateUrl:'/index.html', controller: MyController}).
     otherwise({redirectTo: '/'});
}]);

index.html和host.jsp未显示简洁及其无关紧要。

控制器从Ajax请求中获取一些数据,将其中的一些数据存储在var MyController=['$scope','$http','$location',function ($scope, $http, $location) { //do some fancy stuff if($scope.myAttribute===undefined){ $scope.myAttribute=someDataFromHttpRequest; } $location.search(someParameters); }]; 中以避免再次请求它并将其显示给用户并等待输入。当用户在视图中选择一些数据时,我更新URL查询部分以反映选择更改。但我想通过检查$scope中的数据是否可用来避免后续的Ajax请求。

我面临的问题是$scope始终未定义。它会根据每个请求进行重置。我想我在滥用AngularJS。任何线索?

2 个答案:

答案 0 :(得分:13)

当你离开控制器时,范围会被破坏。我会研究制作一种存储你想要的东西的服务。

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);
}];

服务用于在多个控制器/指令之间共享日期,所以我很确定这是你想要的。

以下是关于它们的文档信息:http://docs.angularjs.org/guide/dev_guide.services.creating_services

答案 1 :(得分:4)

您应该使用服务(或$ rootScope)来存储您要保留的信息。 服务是单件,您可以将它们注入控制器,您设置的任何内容都将在您的应用程序中保留。

当您更改路线时,会删除$ scope,因此它们不会保留。

以下是一个例子:

var myApp = angular.module('myApp',[]);
myApp.factory('SomeService', function() {
  return {
      myAttribute : '12345'
  };
});

var MyController=['$scope','$http','$location', 'myService', 'SomeService',function ($scope, $http, $location, myService, SomeService) {
   //do some fancy stuff
   SomeService.myAttribute; //this is how you access myAttribute
}];

另外我在服务中创建一个函数来通过AJAX获取你想要的值(而不是让它在你的控制器中),所以服务将是这样的:

myApp.factory('SomeService', function() {

    var SomeService = {};

    var myAttribute;

    SomeService.getMyAttribute = function () {

         if(!myAttribute) {

            //run ajax request then populate and return myAttribute

         }
         return myAttribute;
    };
    return SomeService;
});