简体   繁体   中英

How can I assign different ng-model values to several input fields created from one directive

I created a directive to dinamically add different form fields. The problem is that once I add more than one directive based field, the ng-model is duplicated. I'm new to working with directives,hope you can help.

    var app = angular.module('app', []);
      angular.module('app').controller('MainCtrl', function ($scope, $compile) {

    $scope.add = function(ev,attrs){//$on('insertItem',function(ev,attrs){
      var iact = angular.element(document.createElement('itemactivo'));
      var el = $compile( iact )( $scope );

      //where do you want to place the new element?
  angular.element(document.body).append(iact);

  $scope.insertHere = el;
};

});


// directive
angular.module('app')
 .directive('itemactivo', function () {
   return {
      templateUrl: 'itemactivo.html',
      restrict: 'E',
      link: function postLink(scope, element, attrs) {

       }
        };
       });

I created a plunker with the problem

http://plnkr.co/edit/IDD5KFO7UEOnP8cSuN33?p=preview

Add scope: true in your itemactivo directive. Code should look like below:

angular.module('app')
  .directive('itemactivo', function () {
    return {
      scope:true,
      templateUrl: 'itemactivo.html',
      restrict: 'E',
      link: function postLink(scope, element, attrs) {
       // element.text('this is a chart');
      }
    };
  });

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