2015-04-23 87 views
1

我有一個指令HTML模板是這樣的:動態設置NG-模型是打破

textinput.html

<label for="{{name}}">{{label}}</label> 
<input type="{{type}}" placeholder="{{placeholder}}" id="{{name}}" ng-model="{{name}}"> 

標籤正確輸出,但是輸入字段內一切outputing靜態{{varname}}

如果我刪除了NG-模式是這樣的:

<input type="{{type}}" placeholder="{{placeholder}}" id="{{name}}"> 

它正確地輸出變量,但是當我放入ng模型並動態地爲它賦值時,它會中斷整個輸入。

這是怎麼發生的?

我的目標是能夠創建簡單的1行文字輸入,我可以大規模使用的指令改變,就像這樣:

<textinput name="username" label="Username" type="text" placeholder="Enter Username"></textinput> 
+0

一旦從指令中設置模型,您打算如何訪問模型?如果每次都有所不同,你不會真正知道$ scope上的模型被調用。 – Chris

+0

我試圖通過這樣的指令調用它: '' – Jordash

+1

嘗試設置ng-model = 「name」 – Hoyen

回答

0

終於想通了,你必須通過傳遞NG-模型使用2路這樣的結合:

<textinput type="email" name="userEmail" ng-model="userEmail" placeholder="Email Address..." label="Email"></textinput> 

-

app.directive('textinput', function() { 
return { 
    restrict: 'E', 
    scope: { 
     label:'@label', 
     placeholder:'@placeholder', 
     name: '@name', 
     type: '@type', 
     ngModel: '=ngModel' 
    }, 
    transclude: true, 
    templateUrl: 'directives/textinput.html' 
}; 
}); 

現在模板HTML網絡內您可以在沒有使用ng-model的{{ }}的情況下映射屬性。

例如:

<label for="{{name}}">{{label}}</label> 
<input type="{{type}}" placeholder="{{placeholder}}" id="{{name}}" ng-model="ngModel"> 

現在,這將是超級容易快速地生成可重複使用的表單代碼。