Как получить значения элементов динамически добавленной директивы - PullRequest
0 голосов
/ 16 июня 2019

Я хотел бы знать, как я могу прочитать значения элементов динамически добавленной директивы.

Плункер здесь: http://next.plnkr.co/edit/he81ccvklc8luZB9

var dynamicDirective = angular.module('testapp', []);

dynamicDirective.controller('mycontroller', ['$scope', '$compile', function($scope, $compile) {

      $scope.add = function() {
        angular.element(document.getElementById('container'))
          .append($compile("<textbox></textbox>")($scope));
      }

      $scope.read = function(){
        console.log("Your values");
      }


  }]);

  dynamicDirective.directive('textbox', [function() {
    return {
      templateUrl: 'dynamictextbox.html',
      scope: {

      },
      controller: function($scope) {

      }
    };
  }]);

dynamictextbox.html

<div>
  First name: <input type="text"/> <br/>
  Last name: <input type="text"/> <br/>
  Age: <input type="text"/> <br/>
</div>

index.html

   <body ng-app="testapp">

    <div ng-controller="mycontroller">
      <button type="button" ng-click="add()">Add</button>
      <button type="button" ng-click="read()">Read Values</button>
      <br/>

      <div id="container">

      </div>
    </div>
  </body>

Заранее спасибо.

1 Ответ

0 голосов
/ 16 июня 2019

Вот как я изменил ваш код: рабочий плункер здесь

var dynamicDirective = angular.module('testapp', []);

dynamicDirective.controller('mycontroller', ['$scope', '$compile', function($scope, $compile) {

    $scope.user={
      firstName: '',
      lastName: '',
      age: ''
    }
      $scope.add = function() {
        angular.element(document.getElementById('container'))
        .append($compile("<textbox user='user'></textbox>")($scope));
      }

      $scope.read = function(){
        console.log($scope.user);
      }


  }]);

  dynamicDirective.directive('textbox', [function() {
    return {
      templateUrl: 'dynamictextbox.html',
      scope: {
        user: '='
      },
      controller: function($scope) {

      }
    };
  }]);

dynamictextbox.html

<div>
  First name: <input type="text" ng-model='user.firstName'/> <br/>
  Last name: <input type="text" ng-model='user.lastName' /> <br/>
  Age: <input type="text" ng-model='user.age' /> <br/>
</div>

пользовательский объект будет регистрироваться в консоли.

...