EmberJS 设置控制器
设置控制器
在Ember.js中,有必要设置帮助模板显示检索到的信息的控制器。Ember.js支持两个内置控制器Ember.ObjectController和Ember.ArrayController。这些是模板的模型属性,以及任何其他显示特定属性。
设置model属性以知道要呈现哪个模型,这可以通过使用路由处理程序的setupController钩子来完成。setupController钩子获取第一个参数作为路由处理器的关联控制器。 您还可以设置路由的controllerName属性而不是默认值。
Ember.Route.extend({
setupController: function(controller, model) {
controller.set('model', model);
}
});
在上面的代码中,在路由处理程序的setupController钩子中设置model属性。
例子
<!DOCTYPE html>
<html>
<head>
<title>Emberjs Setting up a Controller</title>
<!-- CDN's-->
<script src="/attachements/w3c/handlebars.min.js"></script>
<script src="/attachements/w3c/jquery-2.1.3.min.js"></script>
<script src="/attachements/w3c/ember-template-compiler.js"></script>
<script src="/attachements/w3c/ember.min.js"></script>
<script src="/attachements/w3c/ember.prod.js"></script>
<script src="/attachements/w3c/ember.debug.js"></script>
</head>
<body>
<script type="text/x-handlebars" data-template-name="application">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
<!-- using the default controller as index -->
<b>Employee Details</b>
{{#each}}
<p>{{index}}. {{empDetails}}</p>
{{/each}}
</script>
<script type="text/javascript">
App = Ember.Application.create({});
App.IndexRoute = Ember.Route.extend({
//Setting up the model property
model: function(){
//declaring the array values
return [
{firstName: 'Mack', lastName: 'KK'},
{firstName: 'Micky', lastName: 'SK'},
{firstName: 'Smith', lastName: 'KD'}
];
}
});
App.IndexController = Ember.ArrayController.extend({
//define name of the array controller
itemController:'name'
});
App.NameController = Ember.ObjectController.extend({
//Defining the computed property empDetails, that holds firstName and lastName as values
empDetails: function(){
//returning the computed property values
return this.get('firstName')+ ' . ' + this.get('lastName');
}.property('firstName', 'lastName'),
//Defining the computed property index, that holds an array index values
index: function(){
//defining the array index as target to get an index values of an array
return this.get('target').indexOf(this);
}.property('target.[]')
});
</script>
</body>
</html>
输出
让我们执行以下步骤,看看上面的代码如何工作:
将上面的代码保存在 routing_cntrler.html 文件中
在浏览器中打开此HTML文件。