简体   繁体   中英

Why doesn't AngularJS ng-click directive work inside generated search results

I have defined a simple ng-click directive that happens to be inside of generated search results, but this directive doesn't work and I don't know why.

My app uses a index.html file in which AngularJS is bootstrapped and in which a controller is defined:

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<body ng-controller="MainCtrl">
<main>
...
@@include('partials/search-results.html', {"title": "Results", "classTitle": "title_tablet-centered title_results" })
</main>
@@include('partials/footer.html')
</body>
</html>

The generated search results appear where the partial @@include /partials/search-results.html has been included. I don't have a view (eg, via <div ui-view> ) explicitly defined in index.html .

I'm using Algolia instantsearch for search, so within search.js I use an Algolia hits widget to display the list of results according to this template:

hitTemplate =
'<li class="hit">' +
'<div>
'<h5>{{{name}}}</h5>' +
'<p>{{{description}}}</p>' +
'<a href="#" ng-click="showDetails()">Read More</a>' + '</div>' +
'</li>';

The widget adds the ng-click="showDetails()" directive to the "Read More" button in each hit.

MainCntrl.js

(function() {
  function MainCtrl($scope) {

    $scope.showDetails = function(){
        console.log("Button clicked");
    };

  }
  angular
    .module('myApp')
    .controller('MainCtrl', ['$scope', MainCtrl]);
})();

Behavior: When I click on the "Read More" button in any of the search results, not only is no message logged to the console, but the search results get cleared and no error message appears in the console.

Question: Given that the search-results partial (and showDetails() directive) seem to be within the scope of ng-app, why doesn't the ng-click directive work?

It is because the new DOM generated element are not $compiled. Angular needs to know about those new DOM element created to be included in the $digest cycle. You need to manually $compile your template once generated. You could directly get the wrapping div and compile the innerHTML once the search is done

What do you think ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM