【问题标题】:Angularjs push array to scopeAngularjs将数组推送到范围
【发布时间】:2016-11-24 12:55:57
【问题描述】:

我无法将数组推送到作用域并在此之后清空数组。

我启动函数ng-click="addInput() 向数组$scope.info.sites = []; 添加一个新表单,其中包含另一个数组meta_keys:$scope.tags

如果我再次单击ng-click="addInput(),将生成表单,但已经填写了数据。表示每个 meta_keys:$scope.tags 上的相同值。我想我需要在生成新数组之前清空数组。 或者我走错路了。感谢您的帮助。

codepen.io

html

<div ng-app="myApp" ng-controller="myCtrl">
  {{name}}

<form>
 <div class="form-group"> 
  <label for="txtDevice" class="control-label">Domain Name:</label>
  <input type="text" class="form-control" ng-model="info.name" id="txtDevice">
 </div>
 <div class="form-group">
   <label for="txtIP" class="control-label">IP Address:</label>
   <input type="text" class="form-control" ng-model="info.ip" id="txtIP">
 </div>
 <div class="form-group">
    <label for="txtUsername" class="control-label">Logo:</label>
    <input type="text" class="form-control" ng-model="info.logo" id="txtLogo">
  </div>

<div class="form-group" ng-repeat="site in info.sites track by $index">
  <h4>Seite {{$index+1}}</h4>
<label type="txt" class="control-label">Title</label>
<input type="txt" class="form-control" ng-model="site.site_title" /><br />
<label type="txt" class="control-label">Desc</label>
<input type="text" class="form-control" ng-model="site.meta_desc"><br />
<label type="txt" class="control-label">Meta Keys</label>
<!-- <input type="text" class="form-control" ng-model="site.meta_keys"> -->
<tags-input ng-model="tags" ></tags-input>
</div>

</form>
  <button ng-click="addInput()">+add more inputs</button>
{{info | json}}
  <hr>


  tags = {{tags | json}}

</div>

script.js

angular.module('myApp', ['ngTagsInput'])
    .controller('myCtrl', function($scope, $http){
      $scope.name ="myName"  ;
      $scope.info = {};
      $scope.info.sites = [];
      $scope.tags = []; 


      $scope.addInput = function() { 
        //$scope.tags = []; 
         $scope.info.sites.push({
                          site_title:'',
                          meta_desc:'',
                          meta_keys:$scope.tags})

 }
      // $scope.info.sites.meta_keys = [];

});

【问题讨论】:

  • 您的问题不是很清楚您在寻找什么,您能否详细说明一下并将您的代码与您的问题相关联。我认为,您的代码和问题不同步且令人困惑。

标签: angularjs angularjs-scope angularjs-ng-repeat


【解决方案1】:

只需替换行

<tags-input ng-model="tags" ></tags-input>

<tags-input ng-model="site.tags" ></tags-input>

希望对你有帮助:)

【讨论】:

  • 为什么它在 site.tags 中可用?我在文件顶部定义了一个 $scope.tags = [] 。我怎样才能设置数组的文本值?
  • 看,问题是 $scope.tags 意味着这个 ngmodel 对每个人都是通用的。如果您在 $scope.tags 中添加任何元素,它将适用于所有人。与其把它放在一起,你应该把所有的标签放在它们自己的变量中,即'site'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-02
  • 2016-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-29
  • 2016-12-23
相关资源
最近更新 更多