2013-04-12 79 views
3

我正在研究Angular的CRUD詳細信息屏幕,並希望重新使用單個模板。這裏的初始模板僞代碼,編輯屏幕的原油開始...CRUD詳細信息屏幕,有條件的新信息或編輯

<h1>{{fixtureType.Label}}</h1> 
<form> 
    <span>Fixture Type Details</span> 
     <label>Type</label> 
     <input>{{fixtureType.Type}}</input> 
     <label>Watts</label> 
     <input>{{fixtureType.Watts}}</input> 
     <label>Cost</label> 
     <input>{{fixtureType.Cost}}</input> 
</form> 

假設我希望有條件地使用相同的模板作爲屏幕爲好,這將是這個樣子

<h1>New Fixture Type</h1> 
<form> 
    <span>Fixture Type Details</span> 
     <label>Type</label> 
     <input/> 
     <label>Watts</label> 
     <input/> 
     <label>Cost</label> 
     <input/> 
</form> 

如果這是直接的JavaScript,像bIsEdit = fixtureType != null一個簡單的條件會做的伎倆。從我讀過的東西到目前爲止,沒有任何條件或方法可以將一大塊JS放入角度視圖..,或者是我在哪裏達到自定義指令過濾器

現在我可以有2個視圖,並適當地處理路由,但寧願有一個避免代碼重複。

那麼什麼是角度的方式來處理這樣的事情?

+1

你不能只是編輯一個空的模式? –

+0

我喜歡這個想法,但是目前JS並不知道FixtureType模型看起來像什麼,除非它來自服務器。我可以想到的兩個選項1.在客戶端上製作一個看起來像FixtureType的對象2.將服務器放在空白的FixtureType上 - 這聽起來很粗糙。 – quickshiftin

+0

實際上,經過一些實驗後,我可以逃脫w /填充空白的匿名對象來代替模型,並且在控制檯上沒有任何投訴。適合我!但是我也從馬克提供了一個線索來切換路線,關於我在評論他的答案時採取的方法的更多細節。 – quickshiftin

回答

3

我寧願爲每個路線分開。爲了保持編輯和新的HTML在一起,你可以使用ng-switch有兩個基本的模板,但考慮把他們雙雙進入一個部分,所以你可以NG-包括它在兩種不同的觀點:

<span ng-switch on="mode"> 
    <span ng-switch-when="edit"> 
    <h1>{{fixtureType.Label}}</h1> 
    <form> 
     <span>Fixture Type Details</span> 
     <label>Type</label> 
     <input ng-model='fixtureType.Type' ...> 
    ... 
    </span> 
    <span ng-switch-default> 
    <h1>New Fixture Type</h1> 
    <form> 
     <span>Fixture Type Details</span> 
     <label>Type</label> 
     <input ng-model="fixtureType.Type" ...> 
    ... 
    </span> 
</span> 
+0

如果您嘗試使用包含,看起來好像開關有些不同。問題是'{{fixtureType。 }}模板中的綁定。即使使用外部模板中的'ng-switch',您仍然必須處理包含模板中的那些綁定。最後,我將你的建議混合在一起,開啓路線並按照Mike的建議使用空白模型。這種情況下的'切換'在控制器中完成。其中代碼要麼泵入一個null FixtureType(讀取:'{}'),要麼根據路由提供的id命中服務器。 – quickshiftin

3

我用以下接近,以儘量減少重複形式時,新的和可編輯的版本之間的差異是不是太複雜:

<form ng-submit="mySubmitMethod()"> 
<!-- fields models bound to "activeItem"--> 
    <button > 
    <span ng-show="editMode>Update</span> 
     <span ng-show="!editMode">Create</span> 
    </button> 
</form> 
$scope.activeItem={}; 
    $scope.editMode=false; 
    $scope.mySubmitMethod=function(){ 
     if($scope.editMode){ 
      /* do update of existing*/ 
     }else{ 
      /* process new form*/ 
     } 
     $scope.resetform() 
    }); 

    $scope.EditUser=function(user){ 
     $scope.editMode=true; 
     $scope.activeItem=angular.copy(user); 
    }) 

    $scope.newUser=function(){ 
     $scope.editMode=false; 
     $scope.activeItem={}; 
    }) 
+0

非常相似,我結束了。另外,我不知道'ng-show',謝謝! – quickshiftin