Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

javascript - How can I unbind(remove) angular models when not in DOM

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

 <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" />{{del}}
     </div>
     <input type="text" ng-model="del.a2" />
     {{del}}
 </div>

Initially the value of del is {} and ng-if is false the property a1 is under ng-if condition. Test Case :

step 1 : toggle the ng-if to true so that a1 is visible

step 2 : enter some value into a1 (you can anytime enter value in property a2)

step 3 : now if i again toggle ng-if to false what I'm looking for is the property a1 is to be removed from model.(i.e i just want angular to bind those models which are visible on DOM) like this

Here is the FIDDLE for the above test case.

I guess the problem is with model used as object. but I need a solution in model as object only as I have done lot of coding based on this.

Hope I'm clear with the question.

pls Help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...