AngularJS的基本操作。
1. angular.module用于为程序定义模块,从一开始的注册模块开始。
假设如果你仅希望项目中使用一个模块,你可以如此定义:
// app.js angular.module("appModule", []);
如果希望在模块中添加元素,你可以通过名称调用模块向其中添加。例如: formatFilter.js 文件包含以下元素:
// formatFilter.js // 通过名称获取模块 var app = angular.module("appModule"); // 向模块中添加filter app.filter("formatFilter", function() { return function(input, format) { return Globalize.format(input, format); } }})
如果你的应用包含多个模块,注意在添加模块时添加其它模块的引用。例如,一个应用包含三个模块app、controls、和data :
// app.js (名称为app的模块依赖于controls和data模块) angular.module("app", [ "controls", "data"]) // controls.js (controls 模块依赖于data 模块) angular.module("controls", [ "data" ]) // data.js (data 模块没有依赖项,数组为空) angular.module("data", [])
2. Constant 常量设置。用于定义全局变量。
'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定义全局变量
3. Config 用于设置路由。
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' }); }]);
4. 如何使用全局变量
'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,赋值 }]);
PS:可以在浏览器中查看效果。
<div data-ng-controller="PhoneListCtrl"> {{test.test1}} {{constanttest}} {{test2}} </div> 结果:test111 this is constanttest tank

浙公网安备 33010602011771号