3

我可以在角度模块中加载一些数据吗?我尝试使用 .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。是否有可能在模块初始化的生命周期中调用一次?或者其他方式是什么?

4

1 回答 1

3

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

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

应用程序.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,当遇到路由时,例如#/viewrouteprovider 会查找它并提供正确的模板并调用适当的控制器。我相信这是您想要实现的那种设置。

于 2013-04-25T13:32:39.693 回答