2015-10-06 61 views
0

我必須做一個選擇框,我可以選擇一個名稱,我選擇名稱後,我必須顯示2個值,dateOfBirth和dateOfBirth與過濾器,所以你可以看到年齡例如19歲)AngularJS選擇後顯示2個值

但我的問題是,它顯示從dateOfBirth的所有值。

爲了更好地理解看這個:http://jsfiddle.net/9obhfm5c/1/

模板:

<div ng-app="mainApp"> 
<div ng-controller="ExampleController"> 
     the birthday of 
     <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect"> 
       <option ng-repeat="option in data.availableOptions" value="{{option.dateOfBirth}}"> 
        {{option.vn}} 
      </option> 
     </select> 
     is {{data.repeatSelect}} and is <span ng-model="data.repeatSelect" ng-repeat="option in data.availableOptions | filter:data.repeatSelect">{{ option.dateOfBirth | ageFilter }}</span> years old 
     <br/><br/> 
</div> 

JavaScript代碼:

var mainApp = angular.module("mainApp", []); 
mainApp.controller('ExampleController', ['$scope', function($scope) { 
    $scope.data = { 
    repeatSelect: null, 
    availableOptions: [ 
     {vn:'Mike', an:'Johnson', dateOfBirth: '1996-03-11'}, 
     {vn:'Curry', an:'Muisjes', dateOfBirth: '1992-03-11'}, 
     {vn:'Jan', an:'Peters', dateOfBirth: '1995-03-11'} 
    ], 
    }; 
}]); 
mainApp.filter('ageFilter', function() { 
     function calculateAge (birthday) { 
      var date = new Date(birthday); 
      var ageDifMs = Date.now() - date.getTime(); 
      var ageDate = new Date(ageDifMs); 
      return Math.abs(ageDate.getUTCFullYear() - 1970); 
     } 

     return function (birthdate) { 
      return calculateAge(birthdate); 
     }; 
    }); 

你可以看到,它輸出的所有歲月(192320)並且當您選擇1名稱時,它會顯示適當的價值e,但是我希望它首先被清空,並在選擇之後顯示年齡。

回答

0

我不知道它對你有好處,但你可以在沒有選擇任何東西時隱藏它。

您可以通過添加ng-show =「data.repeatSelect!= null」來實現。

http://jsfiddle.net/arielcessario/9hfvkL32/

<div ng-controller="ExampleController"> 
     the birthday of 
     <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect"> 
       <option ng-repeat="option in data.availableOptions" value="{{option.dateOfBirth}}"> 
        {{option.vn}} 
      </option> 
     </select> 
     is {{data.repeatSelect}} and is <span **ng-show="data.repeatSelect != null"** ng-model="data.repeatSelect" ng-repeat="option in data.availableOptions | filter:data.repeatSelect">{{ option.dateOfBirth | ageFilter }}</span> years old 
     <br/><br/> 
</div> 
+0

THX的男人!如果沒有人給出另一個答案,我可以使用這個解決方案! – Draity

+0

沒問題!有一個問題,你出於某種原因使用過濾器,或者只是爲了練習?問候! –

+0

只是爲了練習;) – Draity