Ng click and / or ng change

Morning, that's what happens.

I did dev, it worked fine, but only with firefox. When I tested it with chrome ... it didn't work at all.

So I have a choice and I want to store the selected value so I can process it later.

Here is my angular:

 if ($scope.dateTemp == "") {
     $scope.displayNotification('error', "Empty date");
 } else {
     alert($scope.dateTemp);
     //dateTemp treatment
 }

      

and

$scope.saveDate = function(dateMin){
            alert(dateMin);
            $scope.dateTemp=dateMin;
        };

      

My opinion:

<p>Select date
    <br/>
    <select ng-model="date_selection" ng-change="saveDate(dateMin)">
        <option ng-repeat="dateMin in listeDate" track by $index>{[{dateMin}]}</option>
    </select>
</p>

      

When I tried this I got undefined with my warning (the btw saveDate function is just a setter for $scope.dateTemp

)

Also, when I try to do it, it works fine, but not with chrome.

    <select ng-model="date_selection">
        <option ng-click="saveDate(dateMin)" ng-repeat="dateMin in listeDate" track by $index>{[{dateMin}]}</option>
    </select>

      

Thank you for your advice.

+3


source to share


2 answers


track by $index

must be included in the directive ng-repeat

.

<select ng-model="date_selection" ng-change="saveDate(dateMin)">
        <option ng-repeat="dateMin in listeDate track by $index">{[{dateMin}]}</option>
</select>

      

track by

is a directive option ng-repeat

that helps identify a unique element in an array.

A short example:



function TodoCtrl($scope) {
  $scope.date_selection;
  $scope.listeDate = ['date1','date2'];
  $scope.saveDate=function(date_selection){
    console.log(date_selection);
  }
}
      

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="TodoCtrl">
   <select ng-model="date_selection" ng-change="saveDate(date_selection)">
        <option ng-repeat="dateMin in listeDate">{{dateMin}}</option>
   </select>
   {{date_selection}}
  </div>
</div>
      

Run codeHide result


I am testing it and it works in chrome and mozilla.

+1


source


You can also use ng-options inside select tag

Controller:

app.controller('MainCtrl', function($scope) {
  $scope.listeDate = [{"value":1,"text":"date1"},
  {"value":2,"text":"date2"},
  {"value":3,"text":"date3"},
  {"value":4,"text":"date4"}];

  $scope.Print=function(){
    alert($scope.selected);
  }
});

      



HTML:

<body ng-controller="MainCtrl">
    <select ng-options="date.value as date.text for date in listeDate" ng-model="selected" ng-change="Print()"></select>
  </body>

      

Working plunker link

+2


source







All Articles