我有这个脚本来追加新元素:
function(newElements, data, url){
var $newElems = $( newElements );
$('#posts').masonry( 'appended', $newElems, true);
}
并且此按钮是使用此Angularjs代码添加的新元素html的一部分:
<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>
但Angularjs不起作用,仅在附加的元素1中,如何在每个新元素追加中使其工作?
答案 0 :(得分:0)
我想你需要使用事件追加新元素。我使用Angular指令编写了一个示例。你必须$编译元素。
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));
});
}
};
});
&#13;
<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>
&#13;
请注意:我不是角色专家(还是:P)所以我希望这个例子使用最佳做法,否则人们会纠正我。