如何设置动态输入ng-repeat的默认值?

时间:2016-10-13 08:32:54

标签: angularjs ionic-framework

我尝试为某些输入设置默认值。

当我尝试使用离子框架设置

的默认值时
  

NG-值

工作但是当我提交表单时,我永远不会得到默认值。我得到了不确定。 我认为这是因为我无法在渲染表格之前启动我的对象。

但是使用动态输入名称我无法找到方法。

这是我的控制器:

function MyCtrl($scope) {
    $scope.frequences = [];
    $scope.medicaments = {
    15:{dose : 10,frequence :"matin", name:"test1"},
    16:{dose : 15,frequence :"matin", name:"test2"},
    17:{dose : 19,frequence :"matin", name:"test3"},
    };

    $scope.genererDate = function(form) {
            console.log($scope.frequences)
}

我的HTML

<ion-item ng-repeat="(key, value) in medicaments " >

<span class="">{{key}} - {{value.name}}</span>
    <input type="text"  ng-model="frequences[key]['dose']"  ng-init="frequences.key['dose'] = value.dose" >

    <input type="text" ng-model="frequences[key]['frequence']"  ng-init="frequences[key]['frequence'] = value.frequence">

</ion-item> 

我有一个小提琴,ng值在这里不起作用,所以我尝试使用ng-init。

http://jsfiddle.net/hwunpm5q/2/

1 个答案:

答案 0 :(得分:1)

使用{}定义$scope.frequences = {};而不是数组[]

应该通过frequences[key]['dose']而不是frequences.key['dose']

进行访问

&#13;
&#13;
var myApp = angular.module('myApp',[]);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
   	$scope.frequences = {};
  	$scope.medicaments = {
    15:{dose : 10,frequence :"matin", name:"test1"},
    16:{dose : 15,frequence :"matin", name:"test2"},
    17:{dose : 19,frequence :"matin", name:"test3"},
    };
    
    $scope.genererDate = function(form) {
	  console.log($scope.frequences)
     }
  
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">

 <form name="myform" novalidate="" ng-submit="genererDate(myForm)" > 
<ion-item ng-repeat="(key, value) in medicaments " >

<span class="">{{key}} - {{value.name}}</span>
										
<input type="text"  ng-model="frequences[key]['dose']"  ng-init="frequences[key]['dose'] = value.dose" >

<input type="text" ng-model="frequences[key]['frequence']"  ng-init="frequences[key]['frequence'] = value.frequence">

<br/>
</ion-item>	
<br/>

<button class="button button-full buttonValiderTraitement" type="submit" ng-click="Submit">Submit</button>
</form>

</div>
</body>
&#13;
&#13;
&#13;