how to set all the inputs fields to readonly of an ng-template in angular

720 views Asked by At
app.controller('custCtrl',custCtrl);

custCtrl.$inject = ['$element'];

function custCtrl($element)
{
  //call API & get the json
  if(jsonData.readonlyFlag){
   var elems = $element.find('input[type=text]');
   elems .forEach(function(elem) {
    //need to set each elem to readonly
});}
}

But this is throwing the below error.

angular.js:13042 Error: [$injector:unpr] Unknown provider: $elementProvider <- $element <- custCtrl

But I have already included jQuery before angular library

On googling I see few links which says that this is not the right way.

So my question is if I am doing this way, how do I address my requirement else what could be the better way?

Requirement: - how to set all the inputs fields to readonly of an ng-template??

3

There are 3 answers

1
Nainish Modi On
//html
<form id="test">
   <div>
       <input type="text" class="test1" name="test2" />
   </div>
    <div>
        <input type="text" class="test3" name="test4" />
    </div>
</form>

//in your controller 
$('#test').find('input').each(function (idx, input) {
    $(input).attr('disabled','disabled');
});
0
Daniel Webb On

https://docs.angularjs.org/api/ng/function/angular.element

angular.element("#test").find('input').each(function (index, input) {
        input.setAttribute('readOnly', 'true');
    });
0
voskhod On

The problem: you can inject $element into a 'component' controller, not into 'regular' controller - this is why you get the error.

The solution: more proper way would be to set some flag in your controller, e.g. $scope.options.readonly and create a directive that uses this flag to enable/disable inputs.

// In controller:
$scope.options.readonly = false;

// In template:
<input is-readonly="options.readonly" ...>

// Create directive:
app.directive('isReadonly', function() {
    return {
        link: function(scope, element, attrs) {
            scope.$watch(attrs.isReadonly, function(value) {
                element.attr('disabled', value ? 'disabled' : null);
            });
        },
    };
});

JSfiddle: http://jsfiddle.net/5jruhs83/