2015-05-24 40 views
3

我在Angular中動態添加元素。代碼如下。在Angular中添加帶有指令的元素

myelement.after('<input ng-model="phone" id="phone">'); 

該元素被添加,所有工作正常。不過,我認爲我錯過了一個步驟,而且Angular不能識別新元素,因爲稍後我收集數據時,動態添加的元素的值未定義。

實時添加元素的原因是從一開始就不知道輸入的數量,用戶可以根據需要添加儘可能多的元素。實際的代碼是這樣的:

myelement.after('<input ng-model="phone"' + counter + ' id="phone' + counter + '">'); 

對不起,我應該從頭提供完整的示例。請看下面的jsfiddle,添加一些手機(帶值)並列出它們:http://jsfiddle.net/kn47mLn6/4/

請注意,我沒有創建任何新的指令。我只使用Angular標準指令,並且我不想爲此工作創建自定義指令(除非需要)。

回答

0

在角度思維,你應該操縱從JS代碼的DOM。 和使用NG-*指令 ,所以我不知道你的代碼,但我認爲你需要做的僅僅是這樣的:

查看

<button ng-click="showAction()">Show the phone input</button> 
<input ng-show="showPhone" ng-model="phone" id="phone"> 

控制器

app.controller('ctrl', [function(){ 
    $scope.showPhone = false; 

    $scope.showAction = function() { 
    $scope.showPhone = true; 
    }; 
}]); 
0

在Angular之外,您需要使用事件處理程序來識別動態添加的新元素。我沒有看到你的代碼來測試的足夠了,但這裏要說的是這個與$。對()會談的文章: Jquery event handler not working on dynamic content

這裏是一個很好的文章,這將有助於與指令,並可通過解決您的問題創建您自己的指令: http://ruoyusun.com/2013/05/25/things-i-wish-i-were-told-about-angular-js.html#when-you-manipulate-dom-in-controller-write-directives

2

假設您正在使用DOM指令將元素添加到DOM。您可以使用內置的角度服務$ compile。 首先將$ compile服務注入您的指令。然後在你的指令的鏈接函數中,獲取myElement,然後在其中添加你的元素。然後使用angular.element()創建你的元素。然後使用$ compile服務編譯它並傳遞你現在在的作用域(這裏這個作用域是指令作用域)。獲得編譯後的dom元素後,您可以將其追加到myElement之後。

這裏是關於如何從指令動態地添加元素的例子:

var elementToBeAdded = angular.element('<input ng-model="phone" id="phone">'); 
elementToBeAddedCompiled = $compile(elementToBeAdded)(scope); 
myElement.append(elementToBeAddedCompiled); 

如果您使用$編譯您的指令服務添加元素,棱角分明會識別您的動態添加元素。

1

我試圖在不使用指令的情況下完成此操作,但似乎向Angular中的DOM中添加多個元素的最佳方法(也許是唯一正確的方式)是定義自定義指令。

我發現這裏http://jsfiddle.net/ftfish/KyEr3/

HTML

<section ng-app="myApp" ng-controller="MainCtrl"> 
    <addphone></addphone> 
    <div id="space-for-phones"></section> 
</section> 

一個很好的例子的JavaScript

var myApp = angular.module('myApp', []); 

function MainCtrl($scope) { 
    $scope.count = 0; 
} 

//Directive that returns an element which adds buttons on click which show an alert on click 
myApp.directive("addbuttonsbutton", function(){ 
    return { 
     restrict: "E", 
     template: "<button addbuttons>Click to add buttons</button>" 
    } 
}); 

//Directive for adding buttons on click that show an alert on click 
myApp.directive("addbuttons", function($compile){ 
    return function(scope, element, attrs){ 
     element.bind("click", function(){ 
      scope.count++; 
      angular.element(document.getElementById('space-for-buttons')).append($compile("<div><button class='btn btn-default' data-alert="+scope.count+">Show alert #"+scope.count+"</button></div>")(scope)); 
     }); 
    }; 
}); 

//Directive for showing an alert on click 
myApp.directive("alert", function(){ 
    return function(scope, element, attrs){ 
     element.bind("click", function(){ 
      console.log(attrs); 
      alert("This is alert #"+attrs.alert); 
     }); 
    }; 
}); 
相關問題