Error modifying the DOM in Angular

0

I have a small error in one of my scripts working with the sun and angular

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <title>Welcome to LearnKode - A code learning platform</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
</head>

<body ng-app="app">
  <div ng-controller="elementController">
    <div id="testDiv">
      <p>error de angular</p>
      <p>{{name}}</p>
      <p>error de angular</p>
    </div>

  </div>
</body>

</html>
<script>
  var app = angular.module("app", []);
  app.controller('elementController', ['$scope', '$document',
    function($scope, $document) {
      $scope.name = "LearnKode";
      var element = angular.element($document[0].querySelector('#testDiv'))
      element.append("<h2>Append</h2>");
      element.prepend("<h2>Prepend</h2>");
    }
  ]);
</script>

Look at the three elements <p> of the html where I put "angular error". The variable name does not compile to me for being within the labels that I manipulate with angular, nevertheless if I take out of the div the 'p' of means where it says 'name', then if it works to me, it seems to me a strange thing, no ? Note even that the first 'p' does not execute it. Do not you think it is weird angular gentlemen?

    
asked by juan Luna 22.04.2016 в 15:47
source

2 answers

2

The problem you have is that the $ digest cycle is running when you try to modify the sun, so when it finishes it does not know that it had pending things to execute.

The solution is using a setTimeout or if you use lodash _.defer() the code would look like this:

var app = angular.module("app", []);
app.controller('elementController', ['$scope', '$document', function ($scope, $document) {
    $scope.name = "LearnKode";
    var element = angular.element($document[0].querySelector('#testDiv'))

    setTimeout(function() {
      $scope.$apply(function(){

        element.append("<h2>Append</h2>");
        element.prepend("<h2>Prepend</h2>");
      }); //this triggers a $digest
    }, 1);
}]);

I leave this link with the code working. I also add this tutorial on the $ digest

    
answered by 22.04.2016 в 18:24
0

Apart from the error you receive, which seems to be solved with the solution that you have already given in the response of @ Wilfredo, it is a bad practice to modify the DOM from a controller. For this are the directives [1] [2].

In my opinion, you should modify your code by creating a directive and modifying the DOM from it.

[1] link

[2] link

    
answered by 26.04.2016 в 12:11