Subin Sebastian
Subin Sebastian

Reputation: 10997

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.

Upvotes: 2

Views: 7180

Answers (3)

Talha
Talha

Reputation: 1636

I would recommend to use the simple on click and access functions and variables via

angular.element(angular_app_controller_element).scope().var/function()

Upvotes: 0

Ruslan  Ismagilov
Ruslan Ismagilov

Reputation: 1348

You can also use a directive inside ng-repeat element that will know when ng-repeat has finished.

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

Each item in ng-repeat has $index and $last - that is true when item is the last.

app.directive('finishRender', function ($timeout) {
  return {
    restrict: 'A',
    link: function (scope, element, attr) {
      if (scope.$last === true) {
        $timeout(function () {
          $(".result_text").click(function(){
            //do something
          });
        });
      }
    }
  }
});

Upvotes: 3

Nikola Yovchev
Nikola Yovchev

Reputation: 10206

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;
});

Upvotes: 3

Related Questions