【问题标题】:jQuery appended does not set ajax button to the element append附加的jQuery不会将ajax按钮设置为元素附加
【发布时间】:2015-07-15 17:40:46
【问题描述】:

我有这个脚本来添加新元素:

function(newElements, data, url){

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

}

这个按钮是新元素的一部分 html 附加这个 Angularjs 代码:

<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 中,我怎样才能在每个新元素附加中使其工作?

【问题讨论】:

标签: javascript jquery html ajax angularjs


【解决方案1】:

我想您需要使用事件添加新元素。我已经使用 Angular 指令编写了一个示例。你必须 $compile 元素。

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>

请注意:我不是 Angular 专家(还不是 :P),所以我希望该示例使用最佳实践,否则人们会纠正我。

【讨论】:

    猜你喜欢
    • 2012-05-24
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 2016-10-21
    • 2017-12-07
    • 2016-11-07
    相关资源
    最近更新 更多