1

I have this script to append new elements:

function(newElements, data, url){

    var $newElems = $( newElements );
    $('#posts').masonry( 'appended', $newElems, true);

}

and this button is part of the new element html append with this Angularjs code:

<li>
    <a href="" ng-init="unfaved=false" ng-show='unfaved' class="font-icon share-fav-active" ng-click="unfavPost({{Auth::user()->id}},{{$post->id}})"><span class="glyphicon glyphicon-star"></span></a> 
    <a href="" ng-init="unfaved=false" ng-hide='unfaved' class="font-icon share-fav" ng-click="favPost({{Auth::user()->id}},{{$post->id}})"><span class="glyphicon glyphicon-star"></span></a>
</li>

but the Angularjs does not work, only in the element 1 appended, how can I make this work in every new element append?

Jason
  • 15,017
  • 23
  • 85
  • 116
Max
  • 83
  • 8

1 Answers1

0

I suppose you need to append new elements using an event. I've written an example using Angular directives. You have to $compile the element.

var testApp = angular.module("testApp", []);

testApp.controller('someController', ['$scope',
  function($scope) {
    $scope.sayHi = function() {
      alert("Hi!");
    };
  }
]);

testApp.directive('addButton', function($compile) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      $(element).click(function(e) {
        var newBtn = $('<button type="button" ng-click="sayHi()">btn</button>');
        $compile(newBtn)(scope);
        $('#buttonsList').append($('<li></li>').append(newBtn));
      });
    }
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<html ng-app="testApp">

<body ng-controller="someController">
  <ul id="buttonsList">
    <li>
      <button type="button" ng-click="sayHi()">first button</button>
    </li>
  </ul>
  <hr>
  <button type="button" add-button>Add new button</button>
</body>

</html>

Please note: I'm not a Angular expert (yet :P) so I hope the example uses the best practices or people will correct me.

Kostas
  • 1,903
  • 1
  • 16
  • 22