Exploring AngularJS for the first time, I've researched extensively but haven't found a satisfying solution. My goal is to retrieve data from the server and bind it to HTML elements on page load. However, I also need to bind click events to these dynamically generated elements.
app.controller('searchController', ['$scope','$timeout','service','$sce', function($scope, $timeout, service, $sce) {
{
$scope.results=[];
service.getResults(function(data) {
results=data;
});// fetching data from server;
}
I am making an AJAX call to fetch results and updating the scope variable accordingly. In my HTML, I'm using ng-repeat to bind this array as shown 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 attach click events to all elements with the class result_text.
Currently, I achieve this using $watch and $timeout.
$scope.$watch("results", function (value) {
$timeout(function() {
$(".result_text").click(function(){ //do something });
}, 1);
});
Is this approach correct? If I omit $timeout, the click binding code would execute before Angular renders the HTML.