我有一个获得对象的指令:
(venv) [root@z1 myproject]# ./tst.py
3.5.1 (default, Jul 13 2016, 08:50:23)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-16)]
Traceback (most recent call last):
File "./tst.py", line 5, in <module>
from tabulate import tabulate
ImportError: No module named 'tabulate'
(venv) [root@z1 myproject]#
(venv) [root@z1 myproject]# python
Python 3.5.1 (default, Jul 13 2016, 08:50:23)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
.>>> from tabulate import tabulate
.>>>
MyListDirectiveController:
export class MyListDirective implements ng.IDirective {
bindToController = true;
controller = MyListDirectiveController;
controllerAs = "vm";
require = ["^parentDirective"];
restrict = "E";
templateUrl = '/list.tpl.html';
scope = {
detailedObject: "="
};
}
模板(list.tpl.html):
export class MyListDirectiveController implements IMyListScope{
colliRelatedDetails: ColliEventGroup[];
static $inject = ['$scope'];
constructor(scope:any) {
}
}
正如你所看到的,我在<div class="table-responsive">
<table id="listtable"
class="table valigntoptable collapse-table table-striped table-hover">
<thead>
<tr>
<th>
<div class="cursor-pointer" ng-click="vm.sortEventsByNumber()">Number</div>
</th>
<th>
<div class="cursor-pointer" ng-click="vm.$parent.sortEventsByValue()">Value</div>
</th>
</tr>
</thead>
<tbody ng-repeat="Event in vm.detailedObjects">
<tr class="top-padding">
<td>
{{Event.number}}
</td>
<td>
{{Event.value}}
</td>
</tr>
</tbody>
</table>
</div>
中没有排序方法。我尝试解决的方法是在父控制器内(因为我需要另一个类似的列表)。所以我需要调用MyDirectiveController
的方法。但是我如何访问它们?
我无法摆脱孤立的范围,因为我需要双向绑定。否则,当调用排序函数时,列表不会更新。
要在parentDirectiveController
中添加新的排序方法,请注入parentscope然后调用方法。但似乎这不是一个干净的方式。
答案 0 :(得分:1)
有两种方法可以实现这一目标。第一种方法是将函数从父级显式传递给子级作为参数。这更加灵活,但需要在标记中指定功能,这可能是不可取的。 IE:
export class MyListDirective implements ng.IDirective {
...
scope = {
detailedObject: "=",
sortEventsByNumber: "&"
};
}
<my-list-directive detailedObject="vm.object" sortEventsByNumber="vm.numberSorter"></my-list-directive>
另一种选择是在你的指令中使用require
。这会强制父/子关系,这意味着如果将该指令放在不同类型的元素中,则该指令不起作用。
您已将此添加到指令中,但尚未与其挂钩。要访问所需的父控制器,您需要通过链接功能访问它。
export class MyListDirective implements ng.IDirective {
...
require = "^parentDirective",
link: function(scope, elem, attrs, parentInstance) {
//the fourth argument is the controller instance you require
vm.sortEventsByNumber = parentInstance.sortEventsByNumber;
}
答案 1 :(得分:-2)
试试这个:
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="firstname">
<h1>{{firstname}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstname = "John";
$scope.lastname = "Doe";
});
</script>
<p>Change the name inside the input field, and the model data will change automatically, and therefore also the header will change its value.</p>
</body>
</html>