简体   繁体   English

具有Ng重复的动态Ng模型

[英]Dynamic Ng-Models with Ng-Repeat

I have a set of tabs: 我有一组选项卡:

 <tabset class="tab-container">
    <tab id = "tabContent" ng-repeat="tab in tabs" active="tab.active" ng-model = "cmModel"> <!-- the tab highlight directive -->
      <tab-heading>
      <span>{{tab.title}}</span>
      <i class="glyphicon glyphicon-remove" ng-click="removeTab($event, $index)"></i> <!-- the tab close button -->
    </tab-heading>

    <textarea ui-codemirror='cmOption' id="{{ 'Tab ' + ($index+1) }}"  ng-model = "Text"> + "awefwef" + </textarea>

  </tab>
  <button class="btn btn-default" ng-click="addTab()"></button>
</tabset>

I'm attempting to set a dynamic ng-model with ng-model = "Text". 我正在尝试使用ng-model =“ Text”设置动态ng-model。

First of all, I know that if I really want to add dynamic ng-models, I can't have them all the same (need to somehow add $index to Text). 首先,我知道,如果我真的想添加动态ng模型,则不能完全相同(需要以某种方式将$ index添加到Text)。 However, the most pressing issue is that $scope.Text is undefined, even though I clearly have added a textarea with ng-model Text. 但是,最紧迫的问题是$ scope.Text是未定义的,即使我显然已使用ng-model Text添加了textarea。

What am I doing wrong? 我究竟做错了什么?

Thanks. 谢谢。

我认为,如果在选项卡中找不到ng-model的值,它将得到未定义。

Why don't you just make text a property of each tab? 您为什么不只将文本作为每个选项卡的属性? So instead of doing this: 所以不要这样做:

<textarea ng-model="Text[tab.title]"></textarea>

Do this: 做这个:

<textarea ng-model="tab.text"></textarea>
Text[Value]

That implies you're trying to access a property called "Value" on an object called "Text". 这意味着您正在尝试访问名为“文本”的对象上的名为“值”的属性。 If it was just "Text" then angular would create a variable called "Text" on your scope object and all would be well but since you're trying to access a property on the variable before it has actually been created you're getting the reference error. 如果只是“文本”,那么angular会在您的范围对象上创建一个名为“文本”的变量,一切都会好起来,但是由于您试图在实际创建该变量之前访问该属性,所以参考错误。

I'm assuming you have a controller, in which case do: 我假设您有一个控制器,在这种情况下,请执行以下操作:

$scope.Text = {}

within the controller and what you have should work. 在控制器内,您所拥有的应该起作用。

I am assuming the issue you're running into is trying to have each tab have their own scope for the tab title. 我假设您遇到的问题是试图让每个选项卡都有自己的选项卡标题范围。 To work with your current setup, you will need to just have the model for the <textarea> be set to the tab.title itself. 要使用当前设置,您只需要将<textarea>的模型设置为tab.title本身即可。 This way, it will be tied to that particular tab. 这样,它将被绑定到该特定选项卡。

<tabset class="tab-container">
    <tab ng-repeat="tab in tabs" ng-model="cmModel">
        <tab-heading>
            <p>{{tab.title}}</p>
        </tab-heading>
        <br/>
        <textarea id="{{"Tab"+($index+1)}}" ng-model="tab.title"></textarea>
    </tab>
    <p><button class="btn btn-default" ng-click="addTab()">Add Tab</button></p>
</tabset>

Working JSFiddle Demonstration JSFiddle示范工作

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

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