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

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

@mukund : is there any way we can append html in angularjs service not in controller?
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));

4 Comments

.append works with directive but not .prepend to add any div before matched div element.
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.element
@Slimshadddyyy my bad. then prepend should work as well

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.