AngularJS 过滤器
常见的内置的过滤器列表
过滤器 | 描述 |
---|---|
currency | 格式化数字为货币格式。 |
filter | 从数组项中选择一个子集。 |
lowercase | 格式化字符串为小写。 |
orderBy | 根据某个表达式排列数组。 |
uppercase | 格式化字符串为大写。 |
例如 uppercase
可以转大写,但是只支持其中的英文
<div ng-app="myApp" ng-controller="personCtrl">
<p>姓名为 {{ lastName | uppercase }}</p>
</div>
currency
过滤器可以转换成货币格式
<div ng-app="myApp" ng-controller="costCtrl">
<input type="number" ng-model="quantity">
<input type="number" ng-model="price">
<p>总价 = {{ (quantity * price) | currency }}</p>
</div>
orderBy 可以根据指定表达式排列数据
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | orderBy:'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
可以自定义过滤器
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.msg = "Runoob";
});
app.filter('reverse', function() { //可以注入依赖
return function(text) {
return text.split("").reverse().join("");
}
});
AngularJS 服务
location 服务可以返回当前页面的URL地址
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $location) {
$scope.myUrl = $location.absUrl();
});
Angular 中的 $http 服务 可以远程获取数据,可以使用 get 和 post 请求
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
$timeout 服务对应了 JS window.setTimeout 函数。
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.myHeader = "Hello World!";
$timeout(function () {
$scope.myHeader = "How are you today?";
}, 2000);
});
创建自定义服务
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
使用自定义服务
app.controller('myCtrl', function($scope, hexafy) {
$scope.hex = hexafy.myFunc(255);
});
$http 的使用
// 简单的 GET 请求,可以改为 POST
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// 请求成功执行代码
}, function errorCallback(response) {
// 请求失败执行代码
});
最常用的简写模式
$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
此外还有以下方法简写
此外还有以下简写方法:
$http.get
$http.head
$http.post
$http.put
$http.delete
$http.jsonp
$http.patch