2

I'm using ng-model in an input tag, such as

<input ng-model="someModel" type="file" />

At some point in the execution I'm interested in disabling/removing the ng-model so that the input won't be affected anymore by changes to someModel.

I've tried to select the input element and then apply element.removeAttr("ng-model") but the element still seems to be reacting to changes to someModel.

My guess is that this is happening due to the digest cycle. So how do I disable/remove the ng-model?

Daniel Dudas
  • 2,972
  • 3
  • 27
  • 39
bjd54321
  • 422
  • 1
  • 6
  • 13
  • you can use a custom validator that you force to false, then your input will result invalid and will not update your model – fantarama Apr 06 '16 at 15:07
  • Here is another solution (which seems a bit convoluted to me): http://stackoverflow.com/questions/18240168/genuinely-stop-a-element-from-binding-unbind-an-element-angularjs – ippi Apr 06 '16 at 15:09

2 Answers2

2

Have two inputs with ng-if condition. ng-if can remove element from DOM.

<input ng-model="someModel" type="file" ng-if="condition1" />
<input ng-model="" type="file" ng-if="!condition1" />
rupampatel
  • 300
  • 2
  • 11
  • Thank you. This can help as a workaround to achieve what I need. But it actually doesn't answer the question of how to really remove/disable the ng-model. I don't want to have 2 inputs, and remove one of them conditionally, but rather have only 1 input whose ng-model is removed. In my case the input is generated inside a directive, so it complicates things... – bjd54321 Apr 11 '16 at 13:25
1

Here's an example of one way to do this is by using a controller. It basically binds the input to a dummy variable and calls an ng-change function. In the controller you can place your logic on whether or not you want the input to update someModel. In the example, a checkbox determines whether or not to update.

var app = angular.module('app', []);
app.controller('controller', ['$scope',
  function($scope) {
    $scope.update = true;
    $scope.dummyChanged = function(dummy) {
      if ($scope.update) {
        $scope.someModel = dummy;
      }
    }

  }
])
<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@1.5.3" data-semver="1.5.3" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app="app">
  <div ng-controller="controller">
    Type value in here
    <input ng-model="dummy" ng-change="dummyChanged(dummy)" />
    <br />Click here to allow updates to model
    <input ng-model="update" type="checkbox" />

    <pre>
        someModel: {{someModel}}
        update: {{update}}
      </pre>
  </div>
</body>

</html>
Dustin Hodges
  • 4,110
  • 3
  • 26
  • 41