0

I have a "favorite/unfavorite" button which toggles it function once user click it.

<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 am handling click this way;

$scope.Favorite = function (providerContentId) {
        var request = $http({
            method: "post",
            url: "/api/Favorite",
            params: {
                // query string params
            },
            data: {
                providerContentId: providerContentId
            }
        });
        request.then(function (response) {
            // here is it replacing but new ng-click is not working
             var element = angular.element(document.querySelector('#favoriteButton'));
                element.replaceWith(response.data);
        }, function (response) {
            alert(response.data);
        });
    };

while I was searching, I see I would use $compile service to do that, but I could not make it work.

 var content = $(response.data);
                angular.element(document).injector().invoke(function ($compile) {
                    var scope = angular.element(content).scope();
                    $compile(content)(scope);

How can I do that?

Teoman shipahi
  • 47,454
  • 15
  • 134
  • 158

2 Answers2

0

You could try

element[0].outerHTML = response.data; 

instead of

element.replaceWith(response.data);
Josh Kuhn
  • 176
  • 5
  • replacement is fine, but once it is done, ng-click is not working of the new button. – Teoman shipahi May 21 '15 at 23:10
  • Teoman, your problem looks like a duplicate of this post: http://stackoverflow.com/questions/22116470/add-ng-click-dynamically-in-directive-link-function – Josh Kuhn May 21 '15 at 23:13
0

You should use ng-class

Exemple :

  <button ng-class="{'btn-favorite': isFav,'btn-unfavorite': !isFav}" ng-click="Favorite();" id="favoriteButton" class="btn btn-default btn-sm" type="button">
   <span aria-hidden="true" class="@Model.GetFavoriteClass()"></span>
 </button>

And add in your function Favorite() :

$scope.isFav = ! $scope.isFav;
Nicolas2bert
  • 1,142
  • 7
  • 10