我从这里的教程工作时间插入指令:https://fourtonfish.com/blog/2014-01-dynamically-add-directives-in-angularjs-no-jquery/每次按钮被点击
不过,我想创建一个指令,并注射到我的HTML这个每次按钮被点击的时间。经过一番阅读后,我的尝试如下。你会看到,在main.js我有这样的代码:
.directive('addfields',function($compile){
console.log("directive called.");
return function(scope,element){
element.on("click",function(){
var enviroElement = angular.element(document.createElement('enviroVariables'));
var el = $compile(enviroElement)(scope);
console.log(el);
angular.element(document.getElementById('moreEnviromentVariables')).append($compile(el)(scope))
})
}
})
在这里,我试图创建一个元素,编译它,然后它注入。这不起作用,我不知道为什么。我没有收到任何错误。有什么建议么?
全码:
main.html中
<div id ="fullForm" ng-controller="MainCtrl" >
<enviro-variables></enviro-variables>
<div id="moreEnviromentVariables"></div>
</div>
<button-add></button-add>
main.js
'use strict';
/**
* @ngdoc function
* @name jsongeneratorApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the jsongeneratorApp
*/
angular.module('jsongeneratorApp')
.controller('MainCtrl', function ($scope) {
.directive('buttonAdd',function(){
return{
restrict:'E',
templateUrl:'scripts/directives/addbutton.html'
}
})
.directive('addfields',function($compile){
console.log("directive called.");
return function(scope,element){
element.on("click",function(){
var enviroElement = angular.element(document.createElement('enviroVariables'));
var el = $compile(enviroElement)(scope);
console.log(el);
angular.element(document.getElementById('moreEnviromentVariables')).append($compile(el)(scope))
})
}
})
addbutton.html
<div class="row rowmargin">
<div class="col-sm-9">
</div>
<div class="col-sm-3">
<button addfields class="btn"> Add New Variable</button>
</div>
</div>
enviromentVariablesDiv.html
<div id = "formSection">
<div class="row rowmargin">
<div class="col-sm-6">
<input type="text" class="form-control" placeholder="key" id="key" ng-model="key" ng-change="updateJson()" ng-model-options="{debounce: 1000}">
</div>
<div class="col-sm-6">
<input type="text" class="form-control" placeholder="value" ng-model="value" ng-change="updateJson()" ng-model-options="{debounce: 1000}" >
</div>
</div>
</div>
感谢您的回答。我应该更清楚的抱歉,我希望每次单击按钮时都会生成一个新元素,而不仅仅是打开和关闭同一个元素。 –