2014-03-27 97 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