AngularJS 自定义表达式 "filter"?
AngularJS expression with custom "filter"?
我正在使用 GET 加载一些用户配置文件数据,就像这样 -
MainController.js
$http({
method: 'GET',
url: config.serverUrl + '/profile'
}).then(function successCallback(response) {
$scope.userdata = response.data.message.user;
}, function errorCallback(response) {
toastr.error('Something is wrong.');
});
Server response
{
"success": true,
"message": {
"user": {
"id": 36,
"email": "user@gmail.com",
"name": "Rusty Rittenhouse"
}
}
}
现在,我使用以下表达式来显示用户名:
{{ userdata.name }} -> inputs "Rusty Rittenhouse"
如何只显示"Rusty"? 通常我会使用拆分,但由于我是angular的新手,我不知道什么是最好和最简洁的解决方案。
你可以写一个custom filter来做到这一点:
angular.module('myApp', []).filter('firstName', function() {
return function(input) {
return input.split(' ')[0];
};
});
并像这样使用它:
{{ userdata.name | firstName }}
甚至更好:
<div/span ng-bind="userdata.name | firstName"></div/span>
我正在使用 GET 加载一些用户配置文件数据,就像这样 -
MainController.js
$http({
method: 'GET',
url: config.serverUrl + '/profile'
}).then(function successCallback(response) {
$scope.userdata = response.data.message.user;
}, function errorCallback(response) {
toastr.error('Something is wrong.');
});
Server response
{
"success": true,
"message": {
"user": {
"id": 36,
"email": "user@gmail.com",
"name": "Rusty Rittenhouse"
}
}
}
现在,我使用以下表达式来显示用户名:
{{ userdata.name }} -> inputs "Rusty Rittenhouse"
如何只显示"Rusty"? 通常我会使用拆分,但由于我是angular的新手,我不知道什么是最好和最简洁的解决方案。
你可以写一个custom filter来做到这一点:
angular.module('myApp', []).filter('firstName', function() {
return function(input) {
return input.split(' ')[0];
};
});
并像这样使用它:
{{ userdata.name | firstName }}
甚至更好:
<div/span ng-bind="userdata.name | firstName"></div/span>