This Angular directive automatically appends a new HTML item to the page every time my model changes:
app.directive('helloWorld', function($compile) {
return {
restrict: 'AE',
replace: true,
scope:{
arrayItem: '=ngModel'
},
link: function ($scope, ele, attrs) {
$scope.$watch( 'ngModel' , function(){
ele.html('<div ng-click="sendLike({{arrayItem.data.timeline_content}})" class="timeline-item"> Hello {{arrayItem2.data.timeline_content}} </div>');
$compile(ele.contents())($scope);
});
}
};
});
Here is the HTML view for this functionality:
<hello-world ng-repeat="arrayItem in arr" ng-model="arrayItem"></hello-world>
However, I am facing an issue where the ng-click inside the dynamically generated HTML does not work. The recompiling of the newly added section is also not functioning as expected.
UPDATE:
This is the desired outcome:
I am creating a chat application where messages are stored in an array and need to be bound to the HTML view. Upon clicking on each message, an alert() should be triggered within the controller. My controller code looks like this:
app.controller("timelineCtrl", function ($scope) {
$scope.arr={};
$scope.sendLike = function (id) {
alert(id);
};
.
.
.
}
In traditional jQuery, I would use DOM manipulation methods to add new tags for each message. In Angular, I have to bind that array using ng-model or similar approach.
Initially, I thought designing a directive would be a good solution. I can access the main scope from inside the module and make necessary adjustments with the directive. However, changes inside the directive do not reflect in the HTML view as expected, causing issues like ng-click not working for dynamically created tags.