Dynamic elements and scope variables not available in the $http success function block

63 Views Asked by At

I am calling a $http get method and in the success callback, the response that I get, based on that response, in the html, am doing an ng-repeat to iterate over the elements. Also, am maintaining the ids of some divs dynamically based on the $index of the ng-repeat. Now, when I am trying to set the innerHTML of these divs based on their ids, it is giving me an error, as that element has not been created at that time. Am confused regarding what is happening in this case. A mock code snippet below for your reference:

<tr ng-repeat-start= "dataArray in gridData" >
    <td>
        <span ng-bind="expanded ? '-' : '+'" ng-click="expanded = !expanded"></span>{{dataArray.name}}
    </td>
    <td>
        <div id="th_{{$index + 1}}" ng-hide="expanded" ng-repeat="rcL1 in rch.rcs" >
            <div ng-hide="expandedTreeCol" id="to_{{$parent.$index}}_{{$index}}">
            </div>
        </div>
    </td>
</tr>

and here is the js snippet:

$http.get(url)
        .then(function(response) {
            console.log(response);

            $scope.gridData = response.data.data;

            var rch = $scope.rch.rcs;
            var grid_data = $scope.gridData;

            document.getElementById("to_0_0").innerHTML = "1";
        });

while trying to set this innerHTML, it says 'Cannot set property 'innerHTML' of null. However, when i complete the execution of my code, in the dom, i can find the div with that id created. However, it seems it is not yet created when i am in the callback function. Someone please explain what is happening here and how can i set the innerHTML from the js.

Thanks.

1

There are 1 best solutions below

1
On
  1. ng-repeat directive initialize and init watcher on $scope.rch.rcs
  2. send http request, execute callback
  3. document.getElementById("to_0_0") return nothing
  4. As you use $http, it triggers $digest
  5. $digest runs -> watcher on $scope.rch.rcs see changes -> ng-repeat directive renders elements