Reputation: 9226
I append some divs into my HTML page inside Angular
controller
:
jQuery("#mytag").after('<div ng-click="sayHi()">Hi</div>');
and sayHi
method is an Angular
Method inside controller
:
$scope.sayHi = function () {
alert("hi");
};
But ng-click
inside these dynamically created Div's doesn't works! Why?
Upvotes: 1
Views: 1073
Reputation: 16302
So instead of jQuery("#mytag").after('<div ng-click="sayHi()">Hi</div>');
You should have:
function myTag() {
return {
link: function(element) {
element.after('<div ng-click="sayHi()">Hi</div>');
}
}
}
angular.module('yourModule').directive('myTag', myTag);
Then in your view, instead of doing something like:
<div id="mytag"></div>
You should have:
<my-tag></my-tag> or <div my-tag></div>
Update As @Claies points out this too is not a clean approach to a load more or infinite scroll.
I don't know the details of what you are trying to do, so I am going to make some assumptions.
Lets assume we know you only have about 100 records to display. The user probably only wants to see the first 20, but the user then should have the ability to see 20 more after that, and again... until all 100 records are displayed.
In this scenario, it would probably be ok to load all these records into the browser and filter them on the client side in Angular. Again, this may not be your situation. I don't know what you are tying to do.
So in your view you can have a filter that limits these to the first 20 records. Then have an action that increases the filter by 20 records. When the filter limit is greater or equal to the number of records, hide the view more button.
<div ng-repeat="record in vm.records | limitTo : vm.display">
{{ record }}
</div>
<button ng-show="vm.enableLoadMore" ng-click="vm.showMore()">Load More</button>
In your controller for this view, using the controllerAs
syntax:
function RecordsController() {
this.records = [ . . . ]; // your records
this.display = 20; // number of records to display
var self = this;
Object.defineProperty(this, 'enableLoadMore', { get: function() {
return self.records >= self.display;
}})
}
RecordsController.prototype.showMore = function() {
this.display += 20;
}
Upvotes: 2
Reputation: 1183
angular compiles html when it's initialised first time only ,, if you want to recompile it you can inject $compile service into your controller and use it like this
$compile(element)(scope)
but this is not a proper way to dynamically append elements in angular can you tell me what exactly are you trying to build??
Upvotes: 2