@wddpct
2017-04-03T13:25:30.000000Z
字数 2947
阅读 1907
AngularJS
AngularJS 应用组成如下:
AngularJS 表达式写在双大括号内:{{ expression }},如{{firstName+lastName}},或是ng-bind,写在html语法的属性内
数字表达式,也可以使用{{quantity * cost}}代替
<div ng-app="" ng-init="quantity=1;cost=5"><p>总价: <span ng-bind="quantity * cost"></span></p></div>
<div ng-app="" ng-init="firstName='John';lastName='Doe'"><p>姓名: {{ firstName + " " + lastName }}</p></div>
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}"><p>姓为 {{ person.lastName }}</p></div>
<div ng-app="" ng-init="points=[1,15,19,2,40]"><p>第三个值为 {{ points[2] }}</p></div>
AngularJS 指令是扩展的 HTML 属性,带有前缀 ng-。
<div ng-app="" ng-init="firstName='John'"><p>在输入框中尝试输入:</p><p>姓名:<input type="text" ng-model="firstName"></p><p>你输入的为: {{ firstName }}</p></div>
4. ng-repeat 指令会重复一个 HTML 元素
<div ng-app="" ng-init="names=['Jani','Hege','Kai']"><p>使用 ng-repeat 来循环数组</p><ul><li ng-repeat="x in names">{{ x }}</li></ul></div>
5. 自定义指令,要调用自定义指令,HTML 元素上需要添加自定义指令名。
使用驼峰法来命名一个指令, runoobDirective, 但在使用它时需要以 - 分割, runoob-directive:
<body ng-app="myApp"><runoob-directive></runoob-directive><script>var app = angular.module("myApp", []);app.directive("runoobDirective", function() {return {template : "<h1>自定义指令!</h1>"};});</script></body>
<div ng-app="myApp" ng-controller="myCtrl"><h1>{{carname}}</h1></div><script>var app = angular.module('myApp', []);app.controller('myCtrl', function($scope) {$scope.carname = "Volvo";});</script>
2. 根作用域rootScope可作用于所有的controller中
<div ng-app="myApp" ng-controller="personCtrl">名: <input type="text" ng-model="firstName"><br>姓: <input type="text" ng-model="lastName"><br><br>姓名: {{fullName()}}</div><script>var app = angular.module('myApp', []);app.controller('personCtrl', function($scope) {$scope.firstName = "John";$scope.lastName = "Doe";$scope.fullName = function() {return $scope.firstName + " " + $scope.lastName;}});</script>
| 过滤器 | 说明 |
|---|---|
| currency | 格式化数字为货币格式。 |
| filter | 从数组项中选择一个子集。 |
| lowercase | 格式化字符串为小写。 |
| orderBy | 根据某个表达式排列数组。 |
| uppercase | 格式化字符串为大写。 |
也可以在服务中自定义函数当做过滤器使用
<div ng-app="myApp" ng-controller="personCtrl"><p>姓名为 {{ lastName | uppercase }}</p></div>
var app = angular.module('myApp', []);app.controller('customersCtrl', function($scope, $location) {$scope.myUrl = $location.absUrl();//当做参数注入到function中});
2. 自定义服务
app.service('hexafy', function() {this.myFunc = function (x) {return x.toString(16);}});//过滤器的一种使用app.filter('myFormat',['hexafy', function(hexafy) {return function(x) {return hexafy.myFunc(x);};}]);<ul><li ng-repeat="x in counts">{{x | myFormat}}</li></ul>
AngularJS 提供很好的依赖注入机制。以下5个核心组件用来作为依赖注入