I have the following code:
<div ng-app="myApp" ng-controller="AngularCtrl">
<a href="#" id="click_btn">Click here</a>
</div>
<script>
jQuery("#click_btn").click(function(){
jQuery(this).replaceWith('<p>Hello {{student.name}}</p><div my-repeater></div>');
});
</script>
Here is my angular code:
var myApp = angular.module('myApp',[]);
myApp.directive('myRepeater', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var myTemplate = "<div>{{rating}}</div>";
for(var i=0;i<scope.items.length;i++)
{
var myItem = scope.items[i];
var text = myTemplate.replace("{{rating}}",myItem.rating);
element.append(text);
}
}
};
});
function AngularCtrl($scope) {
$scope.student = {id: 1, name: 'John'};
$scope.items = [{id: 1, ratings: 10}, {id: 2, ratings: 20}];
}
Here, whenever i click on the button, the element is just getting replaced and not evaluated. I tried with "angular.bootstrap(document);" after document is ready.
But that just evaluates the angular objects. But still the custom directive "my-repeater" is not getting evaluated. Any help on how can i get this done?
First of all, I suppose this is test code, since angular has ng-repeat, which fits your needs.
There are several issues with your code:
1) You shouldn't use myTemplate.replace, but use the $compile service. Inject the $compile service into your directive (add as function param) and use it:
var text = $compile(myTemplate)(scope);
2) Items on the controller will not by accessible in your directive. Add it as a value to your my-repeater attribute:
<div my-repeater='{{items}}'>
In your directive you need to evaluate my-repeater:
var items = scope.$eval(attrs.myRepeater);
3) jQuery(this).replaceWith will not kickoff angular, since it it out of its scope. You need to do it manually by using scope.$apply. But is better to add the click event in the directive link function:
link: function(scope, element, attrs) {
element.on('click', function() {
...
scope.$apply();
});
Edit: Here is a working example.