AngularJS指令消除部分绑定
我想在转换部分中使用指令、转换内容和调用指令的控制器方法:AngularJS指令消除部分绑定,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我想在转换部分中使用指令、转换内容和调用指令的控制器方法: <mydirective> <div ng-click='foo()'> click me </div> </mydirective> app.directive "mydirective", -> return { restrict: 'EACM', transclude: true template: "<div ng-t
<mydirective>
<div ng-click='foo()'>
click me
</div>
</mydirective>
app.directive "mydirective", ->
return {
restrict: 'EACM',
transclude: true
template: "<div ng-transclude></div>"
scope: { } #required: I use two way binding on some variable, but it's not the question here
controller: [ '$scope', ($scope)->
$scope.foo = -> console.log('foo')
]
}
点击我
app.directive“mydirective”,->
返回{
限制:“EACM”,
转移:对
模板:“”
作用域:{}#必需:我对一些变量使用双向绑定,但这不是问题所在
控制器:['$scope',($scope)->
$scope.foo=->console.log('foo')
]
}
我该怎么做呢?从技术上讲,如果您删除
作用域:{}
,那么它应该可以工作,因为该指令不会创建隔离的作用域。(顺便说一句,您需要添加restrict:“E”,
,因为您使用指令作为元素)
我认为从指令调用父范围中定义的操作比从父范围调用指令中的操作更有意义<代码>指令应该是自包含的和可重用的。指令中的操作不应从外部访问
如果确实要执行此操作,可以尝试通过调用
$scope.$broadcast()
,并在指令中添加侦听器来发出事件。希望有帮助。这有点棘手。被转移的作用域不是指令作用域的子级,而是同级。因此,为了从转置元素的ng点击
访问foo
,您必须将foo
分配给正确的范围,即指令范围的同级。确保从链接
函数访问转置范围,因为它尚未在控制器
函数中创建
我有一个不同的答案,这不是一个黑客,我希望它会被接受 请参阅以获取实时演示 下面是我对该指令的用法 请注意,我在2秒后更改了作用域上的值,因此它显示绑定工作 在网上读了很多书后,我明白了以下几点:
- ng transclude指令是transclusion的默认实现,用户可以根据每个用例重新定义它
- 重新定义转换意味着angular将在每个
$digest
- 默认情况下,转换创建了一个新的作用域,它不是孤立作用域的子作用域,而是一个同级作用域(因此hack可以工作)。如果重新定义转置过程,则可以选择编译转置内容时使用的范围即使仍然创建了一个新的作用域,它似乎
- 没有足够的文档来支持transclude函数。我甚至没有在文档中找到它。我在一个房间里找到的
var app = angular.module('plunker', []);
app.directive("mydirective", function(){
return {
transclude: true,
restrict: 'EACM',
template: "<div> {{ name }} <br/><br/> <div ng-transclude> </div></div>",
scope: { },
link: function($scope){
$scope.name = 'Should change if click below works';
$scope.$$nextSibling.foo = function(){
console.log('foo');
$scope.name = 'it works!';
}
}
}
})
$scope.$parent.foo = ...
<div custom-directive custom-name="{{name}}">
if transclude works fine you should see my name right here.. [{{customName}}]
</div>
angular.module('guy').directive('customDirective', function($compile, $timeout){
return {
template : '<div class="custom-template">This is custom template with [{{customName}}]. below should be appended content with binding to isolated scope using the transclude function.. wait 2 seconds to see that binding works</div>',
restrict: 'AC',
transclude: true,
scope : {
customName : '@'
},
link : function postLink( scope, element, attrs, dummy, transcludeFn ){
transcludeFn( scope, function(clone, innerScope ){
var compiled = $compile(clone)(scope);
element.append(compiled);
});
$timeout( function(){
scope.customName = 'this stuff works!!!';
}, 2000);
}
}
});