0

In my AEM component, there is an rte element. all the markup is generated dynamically and I wanted to append an ng-click to call a function. Here is the code for adding RTE${properties.text @context='html'} This is giving me just a class that i am using as selector. My existing code is as follows :

var sdshopNowLink = angular.element('.sdshopNowLink');
sdshopNowLink.on('click', function(){
    $scope.submitshopeCatalog();
});

I was using javascript selectors first but that is not working for the first time. Using $compile is working locally but not after minification.

var sdshopNowLink = angular.element('.sdshopNowLink'); 
sdshopNowLink.attr("ng-click", "submitshopeCatalog()");
compile(sdshopNowLink);

function compile(element){
    var el = angular.element(element);    
    $scope = el.scope();
    $injector = el.injector();
    $injector.invoke(function($compile){
        $compile(el)($scope)
    });     
}

Also the above has some perf issues as well. Is there any other way i can append ng-click & call the function.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • You can attache event handler to the parent element which you have control and delegate that handler to the dynamic one – Sandeep Saroha Mar 20 '19 at 07:23
  • Possible duplicate of [Call angularjs function using jquery/javascript](https://stackoverflow.com/questions/23648458/call-angularjs-function-using-jquery-javascript) – ClydeFrog Mar 20 '19 at 07:31
  • @ClydeFrog Quite similar but your solution won't append the ng-click because i want the function to be called on click only. – Sourav Tomar Mar 20 '19 at 09:34
  • Yes, it is similar. Although, you can use the same functionality, in the example that is given, to serve your needs. – ClydeFrog Mar 22 '19 at 06:30

1 Answers1

0

Like the answer in the duplicate question I stated in the comments. You can use that to serve your needs. Like this:

HTML

<div id="YourElementId" ng-app='MyModule' ng-controller="MyController">
    Hi
</div>

JS Code

angular.module('MyModule', [])
    .controller('MyController', function ($scope) {
    $scope.myfunction = function (data) {
        alert("---" + data);

        // Do something more...
    };
});

// I changed the code here so when element with ID "YourElementId" 
// gets clicked, it executes the anonymous function that calls "myFunction" 
// in the controller "MyController"
window.onload = function () {
    angular.element(document.getElementById('YourElementId')).on('click', function (event) {
        angular.element(event.target).scope().myfunction('test');
    });
}
ClydeFrog
  • 912
  • 1
  • 14
  • 38