T
T
timofy2017-08-12 15:52:35
JavaScript
timofy, 2017-08-12 15:52:35

Function does not work when clicking on an element with the ng-click attribute?

The essence of the question is as follows:
there is such an html code:
<span ng-click="childComment()">Comment 1</span>
and something like this javascript code:

var commentsApp = angular.module('commentsApp', []);
commentsApp.controller("commentsController", function ($scope, $http, $timeout) {

       $scope.childComment = function () {
              console.log('Ok');
       };
       $timeout(function () {
             var span2 = angular.element('<span>')
                            .attr('ng-click', 'childComment()').text('Comment 2');
        }, 1000);
});

Two span elements respectively appear in the browser: "Comment 1" and "Comment 2". When you click on the "Comment 1" element, the $scope.childComment() function fires and "OK" is displayed in the console, but when you click on the "Comment 2" element, nothing happens and nothing appears in the browser console.
At first I thought that the "Comment 2" element was not in the scope of the $scope.childComment() function, but in this case I think that the browser would throw an error that such a function does not exist.
What could be the reason? Maybe in using the $timeout service?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nicholas, 2017-08-12
@timofy

By itself, adding an attribute doesn't tell Angular anything. You need to either: use $compile on the specified piece of DOM, or insert DOM through angular (ng-bind-html)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question