1. 程式人生 > >angularJs設定全域性變數的N種方法

angularJs設定全域性變數的N種方法

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="http://apps.bdimg.com/libs/angular.js/1.5.0-beta.0/angular.min.js" type="text/javascript"></script>
    <script>

		var myApp = angular.module('myApp', []);  

		//方法1 value 
		myApp.value("public",{
		  "Localapi":"/v1/getInfo/",
		  "Versions":"V2.2.3"
		}); 

		//方法2 constant  
		myApp.constant("option", function(){
		   
			return {
				//全域性共用函式
				fn : function(str) {
				  return "text"
				},
				//變數
				Localapi : "/v1/getInfo/",
				//陣列
				array : [200,300,500,600]
			}

		}); 
		  
		//使用,注入public
		myApp.controller("Demo",["$scope","public",function($scope,public){

		     $scope.public = public;
		 
		}])

		//使用,注入public
		myApp.controller("Demo2",["$scope","option",function($scope,option){

		     $scope.option = option();
		 
		}])

    </script>
</head>
<body ng-app="myApp">

	<div ng-controller="Demo">
		{{ public.Localapi }}
	</div>

	<div ng-controller="Demo2">
	    {{ option.Localapi }} <br/>
		<span ng-repeat="(key, value) in option.array">
			({{ key }} -- {{ value }})
		</span>
	</div>

</body>
</html>