首頁  >  文章  >  web前端  >  Angularjs 設定全域變數的方法(圖文教學)

Angularjs 設定全域變數的方法(圖文教學)

亚连
亚连原創
2018-05-19 15:10:422226瀏覽

這篇文章主要介紹了Angularjs 設定全域變數的方法總結的相關資料,需要的朋友可以參考下

AngularJS 設定全域變數的三種方法

#angularjs本身有二種,設定全域變數的方法,加上js的設定全域變數的方法,總共有三種。要實現的功能是,在ng-app中定義的全域變量,在不同的ng-controller裡都可以使用。

1,透過var 直接定義global variable,這根純js是一樣的。

2,用angularjs value設定全域變數 。

3,用angularjs constant來設定全域變數 。

下面用一個例子,來說明,上面3種方法:

實例:

1,在app模組中,定義全域變數

'use strict';

/* App Module */

var test2 = 'tank';     //方法1,定义全局变量

var phonecatApp = angular.module('phonecatApp', [   //定义一个ng-app
 'ngRoute',
 'phonecatControllers',
 'tanktest'
]);

phonecatApp.value('test',{"test":"test222","test1":"test111"}); //方法2定义全局变量

phonecatApp.constant('constanttest', 'this is constanttest');  //方法3定义全局变量

phonecatApp.config(['$routeProvider',        //设置路由
 function($routeProvider) {
  $routeProvider.
   when('/phones', {
    templateUrl: 'partials/phone-list.html'   //这里没有设置controller,可以在模块中加上ng-controller
   }).
   when('/phones/:phoneId', {
    templateUrl: 'partials/phone-detail.html',
    controller: 'PhoneDetailCtrl'
   }).
   when('/login', {
    templateUrl: 'partials/login.html',
    controller: 'loginctrl'
   }).
   otherwise({
    redirectTo: '/login'
   });
 }]);

2,在controller中呼叫全域變數

'use strict';

/* Controllers */

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

phonecatControllers.controller('PhoneListCtrl', ['$scope','test','constanttest',
 function($scope,test,constanttest) {
  $scope.test = test;          //方法2,将全局变量赋值给$scope.test
  $scope.constanttest = constanttest;  //方法3,赋值
  $scope.test2 = test2;         //方法1,赋值
 }]);

3,在html中看一下效果

<p data-ng-controller="PhoneListCtrl">
  {{test.test1}}
  {{constanttest}}
  {{test2}}
</p>

結果:test111 this is constanttest tank

上面是我整理給大家的,希望今後會對大家有幫助。

相關文章:

js深入理解閉包(附上程式碼)

#Javascript陣列循環遍歷(forEach詳解)

JS 全螢幕與退出全螢幕詳解(含程式碼)

#

以上是Angularjs 設定全域變數的方法(圖文教學)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn