Javascript 通过指令属性传递操作
在$observe在指令内部工作的方式上,我可能遗漏了一些东西。我必须使用需要通过其父指令进行通信的子指令:Javascript 通过指令属性传递操作,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,在$observe在指令内部工作的方式上,我可能遗漏了一些东西。我必须使用需要通过其父指令进行通信的子指令: <parent> <button>Change text</button> <child text="child element"></child> </parent> app.directive('button', function() { return { require: '^parent
<parent>
<button>Change text</button>
<child text="child element"></child>
</parent>
app.directive('button', function() {
return {
require: '^parent',
scope: true,
restrict: 'E',
link: function(scope, element, attrs, parentCtrl) {
element.bind('click', function() {
parentCtrl.changeText();
});
},
};
});
app.directive('parent', function() {
return {
restrict: 'E',
scope: true,
controller: function($scope, $element, $attrs) {
var child = $element.find('child');
this.changeText = function() {
child.attr('text', 'new text');
};
}
};
});
app.directive('child', function() {
return {
restrict: 'E',
scope: true,
link: function(scope, element, attrs) {
attrs.$observe('text', function(text) {
element.html(text);
});
}
};
});
更改文本
应用程序指令('按钮',函数(){
返回{
要求:“^parent”,
范围:正确,
限制:'E',
链接:函数(作用域、元素、属性、parentCtrl){
元素绑定('单击',函数(){
parentCtrl.changeText();
});
},
};
});
应用程序指令('父',函数(){
返回{
限制:'E',
范围:正确,
控制器:函数($scope、$element、$attrs){
var child=$element.find('child');
this.changeText=函数(){
attr('text','newtext');
};
}
};
});
app.directive('child',function(){
返回{
限制:'E',
范围:正确,
链接:函数(范围、元素、属性){
属性$observe('text',函数(text){
html(文本);
});
}
};
});
这些代码只是为了说明我正在开发的应用程序中存在的一个问题。所有指令都需要有一个隔离的作用域,因此我无法与它通信。我发了一封信。请随时让我知道,是否有更好的方式与来自父指令的child指令进行沟通
非常感谢,一如既往 我不明白为什么父级和子级必须具有独立的作用域,但如果您只想在父级和子级之间进行通信,可以使用
$emit
和$on
app.directive('parent', function($rootScope) {
return {
restrict: 'E',
scope: true,
controller: function($scope, $element, $attrs) {
var child = $element.find('child');
this.changeText = function() {
child.attr('text', 'new text');
};
$rootScope.$emit('FromParent', somedata);
}
};
});
app.directive('child', function($rootScope) {
return {
restrict: 'E',
scope: true,
link: function(scope, element, attrs) {
attrs.$observe('text', function(text) {
element.html(text);
});
$rootScope.$on('FromParent', function(event, somedata){
//Do something with the data
});
}
};
});
为什么不使用
$emit
和$on
?我知道在我的示例中使用隔离作用域是没有意义的。但在我的项目中,所有这些指令都是独立的和可重用的。这就是为什么我更喜欢隔离范围。我正在循环寻找一种方法,通过更改指令中的属性来触发指令中的事件。@您可以使用中介模式。有一个中心点,例如一个正在侦听事件并将事件发送回应该侦听它们的指令的服务。