Dan*_*zyk 13 angularjs angularjs-directive angularjs-scope
我正在使用angular 1.5,我想将部分DOM提取到一个组件中.
这是我到目前为止所做的:
angular.module('my-app').component("menuItem",{
templateUrl : "lib/menu-item.tmpl.html",
bindings : {
index : "<",
first : "<",
last : "<",
item : "=",
onDelete : "&",
onMoveUp : "&",
onMoveDown : "&"
},
controller : function($scope) {
}
});
Run Code Online (Sandbox Code Playgroud)
模板看起来像这样:
<div>
<aside class="sort-buttons">
<ul>
<li>
<button ng-click="$ctrl.onMoveUp({index : $ctrl.index})"
ng-disabled="$ctrl.first">
<i class="icon icon-up"></i>
</button>
</li>
<li>
<button ng-click="$ctrl.onMoveDown({index : $ctrl.index})"
ng-disabled="$ctrl.last">
<i class="icon icon-down"></i>
</button>
</li>
</ul>
</aside>
<div class="row">
<button class="btn btn-danger btn-icon btn-remove"
ng-click="$ctrl.onDelete({index : $ctrl.index})">
<i class="icon icon-remove"></i>
</button>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我使用这个组件(远未完成!)如下:
<section class="container menu">
<menu-item index="$index" first="$first" last="$last" item="item"
on-delete="removeItem(index)"
on-move-up="moveItemUp(index)"
on-move-down="moveItemDown(index)"
ng-repeat="item in menu">
</menu-item>
<!-- some other display details of `$ctrl.item` -->
</section>
Run Code Online (Sandbox Code Playgroud)
我猜有三个主要问题:
$ctrl在模板中的任何地方使用?有$scope这样的原因,为什么所有的绑定都去了$ctrl而不是$scope?有没有办法改变这个?$index,$first并$last在通过呢?在我看来,它是一个"黄油黄油"传递给他们...谢谢你的帮助.
Deb*_*ppe 16
为什么我必须在模板中到处使用$ ctrl?有$ scope所以为什么所有的绑定都转到$ ctrl而不是$ scope?有没有办法改变这个?
$ scope将以angular 2.0消失.你没有义务使用$ ctrl.我建议您仍然使用带有命名控制器的"controllerAs",以避免模板内部混淆.
controllerAs: "menuItemCtrl",
controller : function($scope) {
},
Run Code Online (Sandbox Code Playgroud)
然后 :
<button ng-click="menuItemCtrl.onMoveUp({index : menuItemCtrl.index})"
ng-disabled="menuItemCtrl.first">
<i class="icon icon-up"></i>
</button>
Run Code Online (Sandbox Code Playgroud)
要在控制器中使用有界变量,必须使用this:
controller : function() {
var self = this;
// self.index contains your index
}
Run Code Online (Sandbox Code Playgroud)
我可以以某种方式拥有像$ index,$ first和$ last传入的值吗?在我看来,它是一个"黄油黄油"传递给他们...
我真的不明白你希望如何传递它们.
这甚至是正确的方法吗?或者我应该使用指令?
当您面向可以显示为组件树的应用程序时,组件是最佳选择.
| 归档时间: |
|
| 查看次数: |
16177 次 |
| 最近记录: |