[AngularJS] Transforming raw JSON data to meaningful output in AngularJS

angular.module('APP', [])

.controller('MainController', function($scope, UserConstants){
var user = {
firstName: 'Benjamin',
lastName: 'Roth'
};
this.user = user;
this.userTypes = UserConstants.types;
})
.service('UserPresenter', function(UserConstants){
var typeFromId = _.memoize(function(typeId){
var obj = _.findWhere(UserConstants.types, { value: typeId});
return obj ? obj.display : '';
}); return {
fullName: function(user){
return user.firstName + ' ' + user.lastName;
},
type: function(user){
return typeFromId(user.typeId);
}
};
})
.factory('UserModel', function(UserPresenter){
function UserModel(props){
_.extend(this, props);
}
UserModel.prototype.fullName = function(){
return UserPresenter.fullName(this);
};
UserModel.prototype.type = function(){
return UserPresenter.type(this);
};
return UserModel;
})
.filter('user', function(UserPresenter){
return function(user, fnName){
return UserPresenter[fnName](user);
};
})
.constant('UserConstants', {
types: [
{ value: '1', display: 'Front end' },
{ value: '2', display: 'Back end' },
{ value: '3', display: 'Full stack' }
]
});
<!DOCTYPE html>
<html ng-app="APP">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="https://cdn.rawgit.com/lodash/lodash/3.0.1/lodash.min.js">
</script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div class="container-fluid" ng-controller="MainController as main">
<div class="row">
<div class="col-sm-3">
<pre>{{ main.user | json}}</pre>
</div>
<hr>
<div class="col-sm-3">
<form>
<div class="form-group">
<label>First Name</label>
<input ng-model="main.user.firstName" type="text">
</div>
<div class="form-group">
<label>Last Name</label>
<input ng-model="main.user.lastName" type="text">
</div>
<div class="form-group">
<label>Type</label>
<select ng-model="main.user.typeId" ng-options="type.value as type.display for type in main.userTypes"></select>
</div>
</form>
</div>
<hr>
<div class="col-sm-3">
<form>
<div class="form-group">
<label>Full Name</label>
{{ main.user | user:'fullName' }}
</div>
<div class="form-group">
<label>Type:</label>
{{ main.user | user:'type' }}
</div>
</form>
</div>
</div>
</div>
</body>
</html>
上一篇:怎样用Google APIs和Google的应用系统进行集成(3)----调用Google 发现(Discovery)API的RESTful服务


下一篇:CSS3秘笈复习:第八章