user3855589
user3855589

Reputation: 1103

ng-click doesn't work with dynamic html

I create dynamic html in html ng-click doesn't work.. My code is as follow

window.imagePicker.getPictures(
            function(results) {
for (var i = 0; i < results.length; i++) {
                    console.log('Image URI: ' + results[i] + " : " +i);
                     var tmpfileName = results[i].substr(results[i].lastIndexOf('/') + 1);
                     var fileName=i+"_"+tmpfileName

                     var image = document.getElementById('addArea');
                     var DOM_img = document.createElement("img");
                     DOM_img.setAttribute("id",fileName)
                     var cancel_img = document.createElement("img");
                     cancel_img.src="img/Action-cancel-icon.png";
                     cancel_img.setAttribute("id","cancel_"+fileName);
                     cancel_img.alt="no image";

                    cancel_img.setAttribute("ng-click","test()");
                    DOM_img.src=results[i];
                     DOM_img.height="100";
                     DOM_img.width="100";
                     image.appendChild(DOM_img);
                     image.appendChild(temp);
                     convertImgToBase64URL(results[i], function(base64Img){

                     $scope.images.push(base64Img);

                     console.log("Added... id  i " + i);


                    });

                }
})

$scope.test=function()
{
alert("hello")
}

I also tried following code

$scope.myHtml+="<img src='"+results[i]+"' height=100px width=100px ng-click='test()'>";
<div id="addArea" ng-bind-html="myHtml">
</div>

but ng-click not working

How can I solve this?

ng-click doesn't work on image.. I simply write test function when i click on image nothing happened.. How can I do this ? please help me to solve this

Upvotes: 1

Views: 1333

Answers (3)

sailens
sailens

Reputation: 1614

You need to compile your element:

$compile(cancel_img)($scope);

Remember to inject $compile in your controller so you can use it:

someModule.controller('MyController', ['$scope', '$compile', function($scope, $compile) {

  // Your code and the $compile goes here

}]);

Upvotes: 1

Phong Nguyen
Phong Nguyen

Reputation: 181

For the reason, attribute of html when you use angularJs such as (ng-click, ng-show, ...) should be enter in html code, because when we run application, compiler will compile attribute such as "ng-click" to javascript before run app

Upvotes: 0

akiva
akiva

Reputation: 2737

dynamic html is a contradictory concept to the way angular works.

if all other (2 way binding) means fail and you really must inject html - I would use ngBindHtml

Upvotes: 0

Related Questions