我從這裏的教程工作時間插入指令: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>
感謝您的回答。我應該更清楚的抱歉,我希望每次單擊按鈕時都會生成一個新元素,而不僅僅是打開和關閉同一個元素。 –