angular.module('myApp', []);
angular.module('myApp').controller('myFormController', function($scope) {
$scope.data = {
i1: "remove",
i2: "all",
i3: "values"
};
});
angular.module('myApp').factory('oneRequiredService', function() {
var service = {};
var container = {};
var observerCallbacks = {};
var isValid = function(groupId) {
var valid = false;
var modelStates = container[groupId];
angular.forEach(modelStates, function(modelValid) {
valid = valid || (modelValid ? true : false);
});
return valid;
};
var isRegistered = function(groupId) {
return container.hasOwnProperty(groupId);
};
var notifyAll = function(key) {
var valid = isValid(key);
if (isRegistered(key)) {
angular.forEach(observerCallbacks[key], function(callback, index) {
callback(valid);
});
};
};
service.register = function(groupId, scopeId, callback) {
this.updateValue(groupId, scopeId, undefined);
if (callback) {
this.registerCallback(groupId, callback);
}
};
service.registerCallback = function(groupId, callback) {
if (callback) {
observerCallbacks[groupId] = observerCallbacks[groupId] || [];
observerCallbacks[groupId].push(callback);
};
};
service.updateValue = function(groupId, scopeId, value) {
container[groupId] = container[groupId] || {};
container[groupId][scopeId] = value;
notifyAll(groupId);
};
return service;
});
angular.module('myApp').directive('oneRequired', function(oneRequiredService) {
return {
restrict: "A",
require: 'ngModel',
scope: true,
link: function(scope, element, attrs, ctrl) {
var modelAttr = attrs["ngModel"];
var linkIdentifier = attrs["oneRequired"];
var updateCurrentState = function(isValid) {
scope._valid = isValid;
};
scope.$watch(modelAttr, function(newVal, oldVal) {
oneRequiredService.updateValue(linkIdentifier, scope.$id, newVal);
});
scope.$watch('_valid', function(newVal, oldVal) {
ctrl.$setValidity('oneRequired', newVal);
});
oneRequiredService.register(linkIdentifier, scope.$id, updateCurrentState);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<body ng-app="myApp">
<form ng-controller="myFormController" name="forms.myForm">
<label for="i_1">i_1</label>
<input id="i_1" name="i1" type="text" one-required="foo-bar" ng-model="data.i1" />
<span> i1-err-one-required: {{forms.myForm.i1.$error.oneRequired}} </span> <br>
<label for="i_2">i_2</label>
<input id="i_2" name="i2" type="text" one-required="foo-bar" ng-model="data.i2"/>
<span> i2 err-one-required: {{forms.myForm.i2.$error.oneRequired}} </span> <br>
<label for="i_3">i_3</label>
<input id="i_3" name="i3" type="text" one-required="foo-bar" ng-model="data.i3"/>
<span> i3-err-one-required: {{forms.myForm.i3.$error.oneRequired}} </span> <br>
</form>
</body>
我也使用指令用來顯示形式的一些fieds信息。 我將表單名稱傳遞給指令,以便指令可以獲得輸入/錯誤/有效...也許$ scope。$ watch in controller或$ scope。$ apply()in directive可以幫助 – AlainIb
您是否可以檢查輸入在控制器中? –
@OlaviSau:我可以但我不知道如何讓其他控制器使用這項服務。 –