如何获取动态添加的指令的元素的值

时间:2019-06-16 11:29:08

标签: angularjs angularjs-directive

我想知道如何读取动态添加的指令的元素值。

在这里插拔: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 :(得分:0)

这是我更改代码的方式: 可工作的here

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>

用户对象将在控制台中登录。