One of the features in my project is a "favorite/unfavorite" button that switches its function when clicked by the user.
<button id="favoriteButton" class="btn btn-default btn-sm" type="button" ng-click="@Model.GetFavoriteClick()">
<span aria-hidden="true" class="@Model.GetFavoriteClass()"></span> @Model.GetFavoriteText()
</button>
In my controller, I handle the click event like this:
$scope.Favorite = function (providerContentId) {
var request = $http({
method: "post",
url: "/api/Favorite",
params: {
// query string params
},
data: {
providerContentId: providerContentId
}
});
request.then(function (response) {
// The content gets replaced here, but the new ng-click doesn't work
var element = angular.element(document.querySelector('#favoriteButton'));
element.replaceWith(response.data);
}, function (response) {
alert(response.data);
});
};
During my research, I came across suggestions to use the $compile service, but I couldn't get it to work properly.
var content = $(response.data);
angular.element(document).injector().invoke(function ($compile) {
var scope = angular.element(content).scope();
$compile(content)(scope);
How can I successfully achieve this?