angularjs - 如何获取动态添加指令的元素值
问题描述
我想知道如何读取动态添加指令的元素值。
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>
提前致谢。
解决方案
这就是我更改您的代码的方式: 在这里工作 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>
用户对象将登录到控制台。
推荐阅读
- python - 如何使用线性数据结构来实现非线性数据结构
- python - Pandas - 根据其他列中的最小值获取值
- nuxt.js - 如何为开发中的热重载启用 nuxt 构建指示器
- azure - 如何在应用服务容器中安装 SSH
- ruby-on-rails - include_blank 不适用于 select_year rails 表单输入 Rails 6
- ios - 什么是 UITableViewCell imageView 边距?
- ansible - Ansible:合并多次使用的项目变量
- performance - Taurus 预请求认证
- pandas - 如何在 Pandas 中重新采样 DatetimeIndex?
- android - 如何配置 Kotlin Androidx 依赖项以进行单元测试以及成功编写单元测试