所以我做了一个指令,并尝试将计数值广播到控制器,但它没有给出正确的值 这是我的代码 http://codepen.io/anon/pen/WGzgdE?editors=1010#anon-login
angular.module('app',[]).directive('requiredCount',function($rootScope){
return {
restrict: 'EA',
require: '^form',
link: {
post: function (scope, elem, attr, ctrls) {// jshint ignore:line
console.log('ctrls.$name', ctrls.$name);
scope.$watch(function () {
if (ctrls.$error.required) {
return ctrls.$error.required;
}
}, function (newValue, oldValue) {
if (newValue && newValue !== oldValue) {
var count = newValue.length;
newValue.forEach(function (item) {
if (item.$error.required) {
// if (item.$valid) {
count--;
// }
}
});
}
});
}
}
};
}).controller('app',function($scope){
$scope.$on('count',function(e,a){
$scope.count =a
})
});
答案 0 :(得分:1)
您缺少表单元素中的name属性和' ng-model'元素属性。
<form name='test' novalidate>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" ng-model="user.email" id="email" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input id="pwd" name="pwd" class="form-control"
type="password" ng-model="user.password" required></input>
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<select name="carlist" class="form-control" ng-model="user.carlist" id="carlist" required>
<option value></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<button type="submit" class="btn btn-default">Submit</button>
</form>
&#34;测试$ error.required.length&#34;只会显示所需字段的数量。
required field count {{test.$error.required.length}}
以下是DEMO - http://codepen.io/anon/pen/jrzZLX?editors=1010#anon-login
答案 1 :(得分:0)
您可以使用表单。$ error.required.length
<div ng-show="form.$invalid">
Sorry but {{form.$error.required.length}} errors found.
</div>