2013-04-25 37 views
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。是否有可能有它会在模块的生命周期中调用一次初始化?或者其他方式是什么?

+0

请指定您想要实现的目的 – 2013-04-25 11:57:40

+0

您在应用程序中缺少控制器和其他一些项目 – lucuma 2013-04-25 13:20:15

回答

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会查找并提供正确的模板并调用相应的控制器。我相信这是你试图达到的那种设置。

+0

并且.run()是否可以将$ scope作为参数? – user2025527 2013-04-25 15:02:28

+0

的想法是,运行正在执行特定于应用程序的事情,并且您的控制器正在执行该页面所需的任何内容。您可能需要为登录代码创建一个服务,并从您的运行/控制器调用您的服务。 – lucuma 2013-04-25 15:04:03