且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angularjs使用指令动态添加和删除元素

更新时间:1970-01-01 07:56:30

我解决了你的问题。你的问题是指令 new-directive 没有 isolate 范围。

I'm solve your problem. Your problem is that directive new-directive no has isolate scope.

jsfiddle 上的实例。

angular.module('app', [])

  .controller("mainCtrl", ['$scope', function($scope) {

  }])

  .directive('newDirective', function($compile) {
    return {
      restrict: 'E',
      replace: true,
      scope: {},
      template: '<ul>' +
        '<li>' +
        '<button ng-click="remove()">Remove {{ind}}</button>' +
        '</li>' +
        '</ul>',
      link: function(scope, element, attributes) {
        scope.ind = Math.round(Math.random() * 100);
        scope.remove = function() {
          console.log(scope.ind);
          element.remove();
        }
      }
    }
  })

  .directive('customerForm', function($compile) {

    return {

      scope: {},

      restrict: 'E',

      transclude: true,

      template: '<div>' +
        '<input type="button" value="addd" name="AAA" ng-click="getData()">' +
        '</div>',

      controller: "mainCtrl",

      link: function(scope, element, attrs, mainCtrl) {

        scope.getData = function() {
          $newDirective = angular.element('<new-directive>');
          element.append($newDirective);
          $compile($newDirective)(scope);
        }

      }
    };
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <customer-form></customer-form>
</div>