Search code examples
angularjsdomgetelementbyid

angularjs - Manipulate dom


I have a textarea that remains ng-empty despite adding a comment through a function. As a result the content is not being binded to the $scope and I am losing the data.

I have tried the following:

angular.element($document[0].getElementById(vm.selectedId)).value = comment;

$document[0].getElementById(vm.selectedId).value = comment;

window.document.getElementById(vm.selectedId).value = comment;

document.getElementById(vm.selectedId).value = comment;

The first effort doesn't work whatsoever (despite having the most ng wrapping.) The rest will appear in the field but do not bind.

I should also note that the text fields that I am trying to add text to are within rows of ng-repeat and so their id's are created using $index...


Solution

  • how about passing the index to your function and then updating the underlying array

    (function() {
        'use strict';
    angular
      .module('myApp', [])
      .controller('myCtrl', myCtrl);
    
       function myCtrl(){
           /* jshint validthis: true */
           var vm=this;
           vm.items = ['one', 'two', 'three', 'four'];
           vm.addComment = function(i){
            vm.items[i] = 'comment';
           }
           
       } 
    
    })();
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app="myApp">
      <div ng-controller="myCtrl as vm">
        <div class="row" ng-repeat="item in vm.items track by $index">
                <textarea ng-model=item></textarea>
                <button ng-click="vm.addComment($index)">add comment</button>
          </div>
        </div>
      </div>