2012-08-07 41 views
9

我的目標是瞭解如何正確使用angularJS。我希望能夠綁定選擇的變量來動態改變使用angularJS的DOM結構。我不認爲我完全理解角度提供的文檔,我還沒有在這裏或其他地方找到任何示例。任何幫助表示讚賞。Angularjs - 用指令或小部件動態改變dom?

這個想法是,我有這種用例,我首先從類型的選擇開始,並從該類型選擇,適當的輸入類型元素將被創建,然後用ng模型記錄(從textareas到例如複選框),一直由angularjs控制器控制以進行驗證/限制。我習慣於在頁面上具有克隆能力的元素,並用jQuery銷燬和創建新的想法,但我一直在閱讀,控制器不應該有這個邏輯,而應該用指令/小部件創建。我沒有看到任何以這種方式被操縱的指令或小部件的例子,所以我甚至不知道如何繼續。我能否以這種方式使用指令來操作DOM,而不僅僅是基於觀察元素的多次操作?

我想要做的例子。

$scope.types = ['Type1','Type2'] 

// something along the lines of... 
$scope.layouts = {'Type1':['textarea','textarea'], 'Type2':['numeric','datepicker']} 

選擇類型1:

  • 顯示2文本區域

選擇類型2:

  • 顯示數字輸入
  • 顯示日期選擇器

謝謝,

-JR。

回答

13

這就是我該怎麼做的。請注意,這只是一個起點。在相應的輸入中仍然有一個與特定值綁定的問題。我希望它有幫助。

標記:

<html ng-app="App" ng-controller="MainCtrl"> 

<body> 

    <component index="0"></component> 
    <component index="1"></component> 
    Current type: {{type}} 
    <button ng-click="toggleType()">Toggle</button> 

</body> 

</html> 

指令:

var ngApp = angular.module('App', []).directive('component', function() { 
    var link = function(scope, element, attrs) { 
    var render = function() { 
     var t = scope.layouts[scope.type][attrs.index]; 
     if (t === 'textarea') { 
     element.html('<' + t + ' /><br>'); 
     } 
     else { 
     element.html('<input type="' + t + '"><br>'); 
     } 
    }; 
    //key point here to watch for changes of the type property 
    scope.$watch('type', function(newValue, oldValue) { 
     render(); 
    }); 

    render(); 
    }; 
    return { 
    restrict : 'E', 
    link : link 
    } 
}); 

控制器:

var MainCtrl = function MainCtrl($scope) { 
    $scope.type = 'Type1'; 
    $scope.types = [ 'Type1', 'Type2' ]; 
    $scope.layouts = { 
    'Type1' : [ 'textarea', 'textarea' ], 
    'Type2' : [ 'number', 'text' ] 
    }; 

    $scope.toggleType = function() { 
    if ($scope.type === 'Type1') { 
     $scope.type = 'Type2'; 
    } 
    else { 
     $scope.type = 'Type1'; 
    } 
    }; 
}; 
+0

這就是我要去的地方,我希望我可以從他們的網站上學到更多的例子。該手錶功能對此非常方便。 這正是我尋找的東西的類型。我感謝幫助! – kman 2012-08-30 06:55:23

+0

(關於指令代碼:)我認爲你不應該在'render'內添加'scope。$ watch',因爲你只需要設置'$ watch'一次。 – mik01aj 2013-04-29 12:50:36

+0

@ m01它實際上是鏈接功能。它實際上是否運行多次? – 2013-04-29 13:11:13

4

我能想到的最簡單的方法就是使用ng-show和ng-hide。

http://jsfiddle.net/cfchase/Xn7PA/

<select ng-model="selected_type" ng-options="t for t in types"> 
</select> 

<div ng-show="selected_type=='Type1'"> 
    <input type="text" id="text1" ng-model="text1"/> 
    <input type="text" id="text2" ng-model="text2"/> 
</div> 

<div ng-show="selected_type=='Type2'"> 
    <input type="number" id="numeric1" ng-model="numeric1"/> 
    <input type="date" id="date1" ng-model="date1"/> 
</div> 

當然,你可以清理它沒有把任何邏輯的HTML,但我不想與控制器多餘的東西模糊焦點。請參考forms documentation。很可能你會主要使用建立在一些自定義構建的驗證中的AngularJS。

至於指令,online docs是密集的,但它會在您嘗試一段時間後點擊。爲了更溫和的介紹,Jon Lindquist在YouTube上有一個hello world教程。指令無疑是在Angular中進行DOM操作的方式。

+0

謝謝,我已經試過這一點,似乎工作,但讓我無法輕鬆地進行一旦我擁有更多元素,就會更改元素。那個視頻肯定有幫助! – kman 2012-08-30 06:53:58