如标题所示,给出以下简单示例:
<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 {
}
})
};
});
但到目前为止,我还没有找到一种在我的指令中绑定表单对象的方法。
答案 0 :(得分:1)
当不使用隔离范围时,指令范围与“父”元素的范围相同。所以这将有效:
<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 {
}
})
};
});
答案 1 :(得分:0)
你能做的是
app.directive('my-directive-test', function() {
return {
restrict:'A',
scope: { someVal: '='}
link: function(scope, element, attrs) {
if (scope.someVal) {
} else {
}
})
};
});
和html
<button my-directive-test myForm="someVal">Hello</button>
someVal可以是$ scope.myForm。$ submit或任何其他值。
有关隔离范围的更多详细信息:https://docs.angularjs.org/guide/directive