Angularjs dynamically adding and removing elements using directive

前端 未结 1 547
孤独总比滥情好
孤独总比滥情好 2020-12-20 00:43

I used directive for creating contact form. Initially i create customerForm directive for displaying customer form. In that form i have one button, when we click on add butt

相关标签:
1条回答
  • 2020-12-20 01:14

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

    Live example on 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="affffd" 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>

    0 讨论(0)
提交回复
热议问题