Skip to content Skip to sidebar Skip to footer

How Can I Unbind(remove) Angular Models When Not In DOM

Here is a simple demonstration of what I'm struggling to achieve.

Solution 1:

You can watch a value using $scope.$watch and delete a1 key from del object when a is set to false

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function ($scope) {
    $scope.del = {};
    $scope.a = false;

    $scope.$watch('a', function(value) {
        if (!value) {

            delete $scope.del['a1'];
        }

    });

})

Please see working demo below

var myApp = angular.module('app', []);
myApp.controller('MyCtrl', function($scope) {
  $scope.del = {};
  $scope.a = false;

  $scope.$watch('a', function(value) {
    if (!value) {

      delete $scope.del['a1'];
    }

  });

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="MyCtrl">
    <input type="button" ng-click="a=!a" value="toggle a" />
    <div ng-if="a">
      <input type="text" ng-model="del.a1" placeholder="a1" />{{del}}</div>
    <input type="text" ng-model="del.a2 " placeholder="a2" />{{del}}
  </div>

Solution 2:

In your example only the models visible in the DOM are watched.

If you mean you want the model value removed from the object then you would need to have a watch on 'a' that knows what values to remove from the model.


Post a Comment for "How Can I Unbind(remove) Angular Models When Not In DOM"