简体   繁体   中英

add ng-click to a div that was added using ng-bind-html

I have a div that is created in javascript using angularjs. Here it is
Js:

$scope.myHTML=$sce.trustAsHtml('<div
 ng-app="mainModule" 
 ng-controller="mainCtrl" 
 ng-click="updateText()" 
 class="squareButton ng-scope"> </div>");

html:

<div ng-controller="mainCtrl" ng-bind-html="myHTML" class="screenDiv"></div>

The problem is that when i click on the div it does not call my updateText() method

$scope.updateText = function()
{
alert("worked");
}

The div does show up. the update method is in the mainCtrl controller.
the ng-click doesnt work what did i do wrong or is this just not supported yet.

Heres the page if it helps http://stevenjohnston.ca/ all of the squares "should" popup the alert but it doesnt.

When you write something in your Html which is not known to Html and you want the angular to know those syntax like 'ng-click' you must compile it through the $compiler service. Otherwise it will be treated as a plain string by the angularj as well as the Html. Use the following code.

function htmlGeneratorController($scope, $compile, $sce){
$scope.myHTML=$compile($sce.trustAsHtml('<div ng-app="mainModule" ng-controller="mainCtrl" ng-click="updateText()" class="squareButton ng-scope"> </div>'))($scope);
}

Hope this will help :)

Is there any particular reason for binding HTML to every square?

It would be easier to just use some grid or table and bind ng-click to each cell.

So you can move controlle outside div

 <body ng-controller="mainCtrl">
    <!-- Create Table or Grid .Inside each cell add-->
    <div ng-click="updateText()"></div>
</body>

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