2015-10-06 51 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