我有这个代码(已更新)
HTML
<body ng-controller="MainCtrl">
<form name="form" novalidate>
<directive form="form.test" required
><input type="text" ng-model="text" name="test" required="true" /></directive>
<button ng-click="click()">Click me</button>
</form>
</body>
Javascript
app.controller('MainCtrl', function($scope) {
$scope.click = function(){
console.log('click');
}
});
app.directive('directive', function() {
return {
transclude: true,
replace: true,
scope: {
form: '=',
},
template: '<div>',
link: function(scope, element, attrs, ctrl, transcludeFn) {
var inputDiv = angular.element('<div>')
transcludeFn(scope, function(clone){
inputDiv.append(clone);
})
element.append(inputDiv);
scope.$watch(function(){
return scope.form.$error;
}, function(newValue){
console.log('newValue', newValue);
}, true)
}
}
});
每次我单击该按钮时,都会收到未定义表单的错误。 在这里试试:http://plnkr.co/edit/pl76wo4AJiGH0m7b5NQd?p=preview
最佳答案
我看到有两件事可以更改,首先我会向文本输入添加一个 ng-model
属性和一个 ng-required
属性,这样错误就会使用模型的 Controller 进行跟踪
<input type="text" ng-model="test" ng-required="true" />
接下来您需要在 $watch 上包含 objectEquality 参数,这样它将监视 $error 对象属性的更改
scope.$watch(function(scope) {
return scope.form[scope.toWatch].$error;
}, function(newValue) {
// newValue will be the $error object from the input
}, true); // notice the last true value here, that's the objectEquality parameter
这是更新的 plnkr:http://plnkr.co/edit/LnGhWgZF5ZbnqRUxh4gP?p=preview
关于javascript - 将表单传递给指令 : undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35049166/