我有一个指令 TreeView ,其中包含呈现的每个项目的嵌套指令(作为分支)。
在两个指令的范围内,我都声明了两个应该与父 Controller 通信的参数。
filter: '&'
//将嵌套指令(分支)中的方法过滤器绑定(bind)到树指令属性中的方法 doSomething(),该属性绑定(bind)到 html 指令,该指令绑定(bind)到 Controller 。
iobj: '='
是应该将作用域对象传递给 Controller 的双向绑定(bind)参数。 (但目前不是)
指令:
app.directive('tree', function () {
return {
restrict: 'E',
replace: true,
scope: {
t: '=src',
filter: '&',
iobj: '='
},
controller: 'treeController',
template: '<ul><branch ng-repeat="c in t.children" iobj="object" src="c" filter="doSomething()"></branch></ul>'
};
});
app.directive('branch', function($compile) {
return {
restrict: 'E',
replace: true,
scope: {
b: '=src',
filter: '&',
iobj: '='
},
template: '<li><input type="checkbox" ng-click="innerCall()" ng-hide="visible" /><a>{{ b.name }}</a></li>',
link: function (scope, element, attrs) {
var has_children = angular.isArray(scope.b.children);
scope.visible = has_children;
if (has_children) {
element.append('<tree src="b"></tree>');
$compile(element.contents())(scope);
}
element.on('click', function(event) {
event.stopPropagation();
if (has_children) {
element.toggleClass('collapsed');
}
});
scope.innerCall = function () {
scope.iobj = scope.b;
console.log(scope.iobj);
scope.filter();
}
}
};
});
HTML:
<div ng-controller="treeController">
<tree src="myList" iobj="object" filter="doSomething()"></tree>
<a ng-click="clicked()"> link</a>
</div>
Controller :
app.controller("treeController", ['$scope', function($scope) {
var vm = this;
$scope.object = {};
$scope.doSomething = function () {
var item = $scope.object;
//alert('call from directive');
console.log(item);
}
$scope.clicked = function () {
alert('clicked');
}
...
目前我可以从指令到 Controller 调用函数$scope.doSomething
。所以我知道我可以从指令访问 Controller 范围。我想不通的是如何将对象作为参数从指令传递回 Controller 。当我运行这段代码时,$scope.object
始终是一个空对象。
我将不胜感激任何有关如何处理此问题的帮助或建议。
最佳答案
&
指令绑定(bind)支持参数传递。举个例子
scope.filter({message: 'Hello', anotherMessage: 'Good'})
message
和 anotherMessage
成为绑定(bind)到指令的表达式中的局部变量:
<tree src="myList" iobj="object" filter="doSomething(anotherMessage, message)"></tree>
这是一个示例 plunker回调参数在模板中设置。
documentation明确指出:
Often it's desirable to pass data from the isolated scope via an expression to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is
increment(amount)
then we can specify the amount value by calling thelocalFn
aslocalFn({amount: 22})
.
关于javascript - 如何以 Angular 将对象从具有隔离范围的嵌套指令传递到父 Controller 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34883666/