append a html include ng-click in angularjs
Asked Answered
D

2

9

i have this code in mycontroller i will add this html() to my html, all it right just ng-click dos not work ! have you an ideas why ng-click dos not work

 var html='<div ng-click="selectedValue('+Value+')">Value</div>' ;
     $('#myDiv').html(html);

   $scope.selectedValue = function(value){
     $scope.val =value;

  };

i have to slect the value displayed in the div by using ng-click function selectedValue

Dickens answered 28/4, 2015 at 17:21 Comment(0)
L
21

use this code:

See pluker

Controller:

var html='<div ng-click="selectedValue(value)">Value</div>',
    el = document.getElementById('myID');

$scope.value='mk';

angular.element(el).append( $compile(html)($scope) )

$scope.selectedValue = function (value) {
    $scope.val = value;
    console.log($scope.val)
};

Html:

<body ng-controller="MainCtrl">
    <div id="myID"></div>
</body>
Legate answered 28/4, 2015 at 17:41 Comment(1)
@mukund : is there any way we can append html in angularjs service not in controller?Plumbic
P
5

You should do DOM manipulation through directive only, Ensure you need to compile element before injecting it.

Code

 var html='<div ng-click="selectedValue('+Value+')">Value</div>' ;
 angular.element(document.getElementByID('myDiv')).append($compile(html)(scope));
Palatinate answered 28/4, 2015 at 17:28 Comment(4)
.append works with directive but not .prepend to add any div before matched div element.Portray
True that. jQuery is already included. Any other alternate in Angular to prepend/inserBefore any element ? Also prepend is part of jqlite - docs.angularjs.org/api/ng/function/angular.elementPortray
@Portray my bad. then prepend should work as wellPalatinate
#39610694Portray

© 2022 - 2024 — McMap. All rights reserved.