zoukankan      html  css  js  c++  java
  • Angularjs 设置全局变量的3种方法

    Angularjs自身有二种,设置全局变量的方法,在加上js的设置全局变量的方法,总共有三种。要实现的功能是,在ng-app中定义的全局变量,在不同的ng-controller里都可以使用。

    1、通过var 直接定义global variable,这根纯js是一样的。

    2、用angularjs value来设置全局变量 。

    3、用angularjs constant来设置全局变量 。

    举一个例子来说明上面3种方法:

    1、 在app模块中,定义全局变量

     /* 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中调用全局变 

    /* 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中看一下效

    <div data-ng-controller="PhoneListCtrl">

        {{test.test1}}

        {{constanttest}}

        {{test2}}

    </div>

    结果:test111 this is constanttest tank

  • 相关阅读:
    Ognl表达式基本原理和使用方法
    Struts的拦截器
    Struts框架的核心业务
    Struts2框架基础
    Struts的文件上传下载
    .JavaWeb文件上传和FileUpload组件使用
    mysql数据库连接与锁查询
    关于MyBatis的@Mapper和@MapperScan注解的一点思考
    Hystrix报错java.util.concurrent.TimeoutException: null
    The Hystrix timeout of 2000ms for the command xxx is set lower than the combination of the Ribbon read and connect timeout, 4000ms.
  • 原文地址:https://www.cnblogs.com/xiaxianfei/p/5337755.html
Copyright © 2011-2022 走看看