简体   繁体   中英

jQuery appended does not set ajax button to the element append

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM