简体   繁体   English

模板中的angularjs动态模型

[英]angularjs dynamic model in template

I need to create dynamic inputs, textareas..etc. 我需要创建动态输入,textareas..etc。 So for each input type I have a separate template. 因此,对于每种输入类型,我都有一个单独的模板。 So a text field template could look like this: 因此,文本字段模板可能如下所示:

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

and what I am trying to achieve is something like this: 而我想要实现的是这样的:

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

so I can create text fields with the same template and have a different model for each one. 因此我可以使用相同的模板创建文本字段,并为每个模板使用不同的模型。 That works actually and gets the data passed, but if I type something in the text field it doesn't get applied to the scope variable. 这实际上可以工作并获取传递的数据,但是如果我在文本字段中键入内容,则不会应用于范围变量。

Here's a fiddle to illustrate this: http://jsfiddle.net/uAm99/2/ 这是一个说明这个的小提琴: http : //jsfiddle.net/uAm99/2/

You could try to implement this feature in "angular directive way". 您可以尝试以“角度指令方式”实现此功能。 It can empower the HTML tag, such as reusable template (just mentioned in your implementation). 它可以授权HTML标签,例如可重用模板(在实现中已提到)。 Here is a simple example: 这是一个简单的示例:

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 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" />'
  };
});

And this is a jsfiddle demo 这是一个jsfiddle演示

Hope it helpful. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM