首页 > 解决方案 > 如何获取动态添加指令的元素值

问题描述

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

Plunker: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) {

      }
    };
  }]);

动态文本框.html

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

索引.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>

提前致谢。

标签: angularjsangularjs-directive

解决方案


这就是我更改您的代码的方式: 在这里工作 plunker

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) {

      }
    };
  }]);

动态文本框.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>

用户对象将登录到控制台。


推荐阅读