Angular.js数据访问 [英] Angular.js data accessor
问题描述
我想学习角,我被困在下面。
我有一个PHP的背景下,大多使用Laravel,并且在Laravel您可以在模型中使用访问。所以,如果你有一个模型用户
,其中有一个姓
和姓
。您可以创建全名
的访问,这将返回两个名字和姓氏的:
I'm trying to learn Angular, and I'm stuck on the following.
I have a PHP background, mostly use Laravel, and in Laravel you can use accessors in your models. So if you have a model User
, which has a firstname
and lastname
. You can create an accessor for fullname
which will return both the firstname and lastname:
public function getFullNameAttribute()
{
return $this->firstname . ' ' . $this->lastname;
}
现在,我愿做同样的事情在角。
我有一个用户UserController的:
Now, I would like to do the same thing in Angular. I have a UserController with a user:
function UserController($scope) {
$scope.users = [
{ firstname: 'John', lastname: 'Doe' }
];
}
在视图我要遍历用户与 NG-重复但
,而不是做
In the "view" I want to loop over the users with ng-repeat
, but instead of doing
{{ user.firstname }} {{ user.lastname }}
我希望能够只用
{{ user.fullname }}
也许这就是所谓的在不同的角度或东西,但我似乎无法找到它......
Maybe it's called differently in Angular or something, but I just can't seem to find it...
感谢您的帮助!
推荐答案
角还没有提供原生模型抽象(这主要与REST风格的通信层处理简单化$资源服务旁)。
但是,这并不意味着你不能写和重新使用自己的自定义模型访问。
Angular does not yet natively provide model abstractions (beside simplistic $resource service which deals mostly with RESTfull communication layer). But that doesn't mean you can't write and re-use your own custom model accessors.
<大骨节病> PLUNKER 骨节病>
app.filter("fullName", function () {
return function (user){
return user && [user.firstName, user.lastName].join(' ');
}
});
app.controller("MainCtrl", [
"$scope",
function($scope) {
$scope.user = {
firstName: 'John',
lastName: 'Doe'
};
}
]);
User fullName: {{user | fullName}}
&NBSP;
<大骨节病> PLUNKER 骨节病>
app.factory('UserService', function ($resource){
// User is an instance of $resource service which
// in this example uses mock server endpoint
var User = $resource('user.json');
// Custom User accessor method
User.prototype.fullName = function(){
return [this.firstName, this.lastName].join(' ');
}
return User;
});
app.controller("MainCtrl", [
"$scope",
"UserService",
function($scope, UserService) {
$scope.user = UserService.get()
}
]);
User fullName: {{user.fullName()}}
这篇关于Angular.js数据访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!