Angular show/hide

by petermorlion

HTML

<body ng-app="myApp">
    <div ng-controller="VehicleDetailsCtrl" >
      
         <select ng-model="selectedValue" check-is-truck>
             <option value="1" data-carType="Car">Car 1</option>
             <option value="2" data-carType="Car">Car 2</option>
             <option value="3" data-carType="Truck">Truck</option>
        </select>
        
       
        <div ng-hide="isTruck">
            Hide if a truck was selected.
        </div>
        
        <br><br>
           Type={{selectedType}}<br><br>
    </div>
</body>

JavaScript

var app=angular.module('myApp',[]);

app.directive('checkIsTruck',function(){
    return function(scope,element,attrs){
        scope.vehicleTypes={},scope.selectedType=false;
        angular.forEach( element.find('option'),function( item,idx){
            scope.vehicleTypes[item.value]=item.dataset.cartype; 
        });  
        scope.$watch('selectedValue',function(){
            scope.selectedType=scope.vehicleTypes[scope.selectedValue];
           scope.isTruck = scope.selectedType=='Truck'
        })
      
    };
})


function VehicleDetailsCtrl($scope) {
    $scope.isTruck = false;
    $scope.selectedValue = null;
   
}