是否有类似初始化模块的角度?

时间:2013-04-25 11:49:44

标签: angularjs

我可以在角度模块中加载一些数据吗?我尝试使用.run(),但只要访问页面就会调用它。例如:假设有2个html页面属于同一个模块:

TestPage1.html:
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="js/angular.min.js"></script>
<script src="js/jquery-1.8.2.js"></script>
<script src="js/app.js"></script>
</head>
<body>
    <p><a ng-href="TestPage2.html">Go to Page2</a></p>
</body>
</html>

TestPage2.html:
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="js/angular.min.js"></script>
<script src="js/jquery-1.8.2.js"></script>
<script src="js/app.js"></script>
</head>
<body>
    <p><a ng-href="TestPage1.html">Go to Page1</a></p>
</body>
</html>

app.js:
var myApp = angular.module('myApp', []);
var cnt = 0;
myApp.run(['$rootScope', '$http', function(scope, $http) {
if(scope.loggedIn == undefined || scope.loggedIn == null) {
    $http.get('rest/userData').success(function(data) {
        cnt++;
        alert(cnt);
        scope.loggedIn = true;
});
}
}]);

当我从一个页面导航到另一个页面时,这个.run()会一次又一次地被调用cnt为1.是否可以在模块初始化的一生中调用它一次?或者另一种方式是什么?

1 个答案:

答案 0 :(得分:3)

似乎你缺少一些基础知识,比如控制器。典型的角度设置是为您的应用设置ng-view并通过路由加载其他页面。这是一个简单的例子:

http://beta.plnkr.co/edit/RnZWeWxTJFri49Bvw50v?p=preview

app.js

var app = angular.module('myApp', []).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/view1', {templateUrl: 'TestPage1.html', controller: Page1Ctrl});
    $routeProvider.when('/view2', {templateUrl: 'TestPage2.html', controller: Page2Ctrl});

    $routeProvider.otherwise({redirectTo: '/view1'});
  }]).run(function () { // instance-injector

    alert('only run on first page load this is where you load data or whatever ONE time');  // this only runs ONE time
  })

 function MainCtrl($scope) {
  $scope.name = 'main';
}

function Page1Ctrl($scope) {
  $scope.name = 'page 1';
}

function Page2Ctrl($scope) {
  $scope.name = 'page 2';
}

HTML:

<html ng-app="myApp" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <link rel="stylesheet" href="style.css">
  <script>document.write("<base href=\"" + document.location + "\" />");</script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
  This is the main page. Main nav:

   <a ng-href="#/view1">Go to Page1</a>&nbsp;&nbsp;
    <a ng-href="#/view2">Go to Page2</a>
 <div ng-view></div>
</body>
</html>

你会注意到html中有一个ng-view,当遇到一个路由,例如#/view时,routeprovider会查找它并提供正确的模板并调用相应的控制器。我相信这是你想要达到的那种设置。