I want to achieve read/write access control for select input using angularjs and angular-ui (particularly ui-select2 feature). Scenario is simple: by using ng-readonly attribute I can control whether given input value can be changed by user or not.
<input id="clientShortName" class="span4" type="text" ng-readonly="readOnly" ng-model="client.shortName" />
<input ui-select2="{ tags: sometags}" id="clientTagsSelection" class="span4" type="text" ng-readonly="readOnly" ng-model="client.tagsSelection"/>
<input type="button" value="Edit" ng-click="readOnly = !readOnly"/>
This works fine for standard angularjs but when I'm trying to use inputs defined by angular-ui it doesn't work (doesn't change the read/write state of input).
Full scenario is covered here: http://plnkr.co/edit/pKs4Tq
Unfortunately the AngularUI ui-select2
directive has no integration with the angularJS ng-readonly
directive.
One way for you to overcome this is to create your own directive and watch for changes on the readOnly
property, like this:
app.directive('csReadonly', function() {
return {
restrict: "A",
link: function(scope, iElement, iAttrs, controller) {
scope.$watch(iAttrs.csReadonly, function(readonly) {
iElement.select2(readonly ? 'disable' : 'enable');
});
}
}
});
And use it like this:
<input ui-select2="{ tags: sometags }" cs-readonly="readOnly" ... />
Plunker: http://plnkr.co/edit/LBFDg2
The advantage of the approach is that, if in the future AngularUI decides to include support for the ng-readonly
, you will only have to replace cs-
with ng-
and you're done.