Rehan Sarfraz Rehan Sarfraz - 14 days ago 5
Javascript Question

Javascript variables not updated after Anuglarjs ng-repeat changes made to DOM

I have an angular app which extracts data from a

JSON
file which populates the webpage via directive template for the user using
ng-repeat
.

When the page is initially loaded, the ID(from the json file) in (p) element is 1.

<p id="pollidholder" style ="display:none" ng-bind-html="item.id">{{item.id}}</p>


Once the user presses a button(Next, ng-click), the ID is updated 2 in the
<p>
element via a directive template. I am using the ID to register the users input.

In my back end Javascript (uservotedd.js), I am using

var pollidholder1 = document.getElementById('pollidholder').innerHTML;


to extract the ID from the
<p>
element.

However, the ID is not updated from 1 to 2 for the var pollidholder even though the
<p>
element is changed on the page itself.

How do I update my Javascript variable once the html
<p>
element has changed? Please help. I would like avoid major rewrite of my code. Note the Alert message is not update to reflect the change in ID when the user hits the submit button.

Please let me know if you have any questions. I am beginner coder at best.

Please find the plunker example here https://embed.plnkr.co/3kIxhW2Iq5lKQm81csln/

Answer

Just don't use onclick in your html here:

<div class="simple-button" onlclick="idchange()" ng-click="change()" style ="font-size: 4vw ">Next</div>

Put all the code of idchange into the change function of the controller, and you will have access to all the variables you need. For example:

$scope.change = function() {
    $scope.indexToShow = ($scope.indexToShow + 1) % $scope.items.length;
    alert($scope.items[$scope.indexToShow].id);
}   

Don't try to dodge angular's encapsulation, using onclick rather than ng-click will cause lots of confusion for beginners. Just use ng-click and you will be fine.

Comments