gpt4 book ai didi

javascript - 如何在没有隔离范围的情况下使用 Angular Directive(指令)中的双向绑定(bind)访问表单对象

转载 作者:行者123 更新时间:2023-12-03 10:08:29 25 4
gpt4 key购买 nike

如标题所示,给出以下简单示例:

<form name="myForm">
<button my-directive-test="myForm">Hello</button>
</form>

app.directive('my-directive-test', function() {
return {
restrict:'A',
link: function(scope, element, attrs) {
// How to get scope.myForm.$submitted, scope.myForm.$errors without isolated scope?
})
};
});

目前我一直在做的是:

<form name="myForm">
<button my-directive-test="{{myForm.$submitted}}">Hello</button>
</form>

app.directive('my-directive-test', function() {
return {
restrict:'A',
link: function(scope, element, attrs) {
scope.formSubmitted = scope.$eval(attrs.myDirectiveTest);
if (scope.formSubmitted) {
} else {
}
})
};
});

但我想要实现的是:

<form name="myForm">
<button my-directive-test="myForm">Hello</button>
</form>

app.directive('my-directive-test', function() {
return {
restrict:'A',
link: function(scope, element, attrs) {
if (scope.myForm.$submitted) {
} else {
}
})
};
});

但到目前为止,我还没有找到在我的指令中绑定(bind)表单对象的方法。

最佳答案

当不使用隔离作用域时,指令作用域与“父”元素的作用域相同。所以这会起作用:

<form name="myForm">
<button my-directive-test="myForm">Hello</button>
</form>

app.directive('myDirectiveTest', function() {
return {
restrict:'A',
link: function(scope, element, attrs) {
if (scope[attrs.myDirectiveTest].$submitted) {
} else {
}
})
};
});

关于javascript - 如何在没有隔离范围的情况下使用 Angular Directive(指令)中的双向绑定(bind)访问表单对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30250832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com