Subin Subin - 5 months ago 45
Javascript Question

Angular JS: binding a click event after angular renders HTML DOM

I am using AngularJS for the first time, I have done some search but could'nt find a satisfactory answer.I am trying to fetch some data from server and binding it to page html elements on page load. But I have to also bind click event of those angular generated html elements.

app.controller('searchController', ['$scope','$timeout','service','$sce', function($scope, $timeout,service, $sce) {
{
$scope.results=[];
service.getResults(function(data) {
results=data;
});// fetches data from server;

}


I am fetching some results using an ajax call and updating the scope variable.
In my html I am using ng-repeat and binding to this array, like below

<div ng-controller="searchController">
<input type="text" class="result_text" ng-repeat="result in results" value="{{result.text}}"></input>

</div>


Now I want to bind the click events on all elements with class result_text

Currently I am doing this using $watch and $timeout

$scope.$watch("results", function (value) {

$timeout(function() {
$(".result_text").click(function(){ //do something });
}, 1);
});


Is this the right approach. If I am not using $timeout it would run the click binding code before the html is rendered by angular.

Answer Source

No, this is not the right approach. There are directives that do that.

replace the ugly $(".result_text").click` in your contorller with:

data-ng-click="someFunction()"  (https://docs.angularjs.org/api/ng/directive/ngClick) 

in your template.

Your results can be like this:

service.getResults(function(data) {
    $scope.results=data;
});