2014-03-27 94 views
0

我需要創建動態輸入textareas..etc。所以對於每種輸入類型,我都有一個單獨的模板。因此,一個文本字段模板看起來是這樣的:模板中的angularjs動態模型

<script type="text/ng-template" id="/input.html"> 
    <input type="text" ng-model="model" /> 
</script> 

什麼,我想實現是這樣的:

<div ng-include="" src="'/input.html'" ng-init="model = var1"></div> 
<div ng-include="" src="'/input.html'" ng-init="model = var2"></div> 

這樣我就可以創建文本字段使用相同的模板,並有不同的爲每一個模型。這實際上工作並獲得數據傳遞,但如果我在文本字段中鍵入一些東西,它不適用於範圍變量。

下面就來說明這個小提琴:http://jsfiddle.net/uAm99/2/

回答

0

你可以嘗試實施「角指令的方式」這一功能。它可以授權HTML標記,例如可重複使用的模板(剛剛在您的實現中提到)。下面是一個簡單的例子:

HTML

<body ng-app="myApp"> 
    <div ng-controller="myCtrl"> 
    <custom-input data="var1"></custom-input> 
    <custom-input data="var2"></custom-input> 
    {{var1}} 
    {{var2}} 
    </div> 
</div> 

JS

angular.module("myApp",[]) 
.controller("myCtrl",function($scope){ 
    $scope.var1 = "foo"; 
    $scope.var2 = "bar"; 
}) 
.directive("customInput",function(){ 
    return { 
    restrict:'E', 
    scope: { 
     data:"=" 
    }, 
    template: '<input type="text" ng-model="data" />' 
    }; 
}); 

這是一個jsfiddle demo

希望它有幫助。

+0

是的,先生你是完全正確的解決方案!你做了我的一天,非常感謝! – Abdelilah