Tuesday, April 22, 2014

Dropdown in ng-grid

The controller:

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

app.controller('bodyController', function($scope, LanguageList) {
  $scope.myData = [{name: "Moroni", language: 'fr'},
                     {name: "Tiancum", language: 'en'},
                     {name: "Enos", language: 'nl'}];
    $scope.gridOptions = {
            data: 'myData',
                enableCellSelection: true,
                enableRowSelection: false,
                enableCellEditOnFocus: true,
            columnDefs: [
                {
                    field: 'language', enableFocusedCellEdit: true,
                    editableCellTemplate: 'language_edit.html',
                    cellFilter : 'LanguageMap'
                },
                {field: 'name', enableFocusedCellEdit: true }

            ],
            canSelectRows: false
        };
        
    $scope.languages = LanguageList;
    
})
.factory('LanguageList', function() {
  return [
      { language_code : 'en', language_title: 'English' },
      { language_code : 'fr', language_title: 'French' },
      { language_code : 'nl', language_title: 'Netherlands' }
      ];
})
.filter('LanguageMap', function(LanguageList) {
  
  return function(input) {
    
    var languagesMatched = LanguageList.filter(function(lang) {
      return lang.language_code == input;
    });
    
    if (languagesMatched.length == 1)
        return languagesMatched[0].language_title;
    else
        return '*unknown language*'
    
    
    return text;
  }
});


Main page
<!DOCTYPE html>
<html ng-app="app">
  
  <head lang="en">
    <meta charset="utf-8">
    <title>Custom Plunker</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    
    <script type="text/javascript" src="ng-grid.js"></script>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="ng-grid.css">
    <script>
      document.write('<base href="' + document.location + '" />');
    </script>
    <script src="app.js"></script>
  </head>
  
<body ng-controller="bodyController">
    <div ng-grid="gridOptions" style="height: 400px">
    </div>
    
    
    {{myData}}
</body>

</html>


language_edit.html, dropdown template:
<select 
ng-cell-input 

ng-options='l.language_code as l.language_title for l in languages'

ng-class="'colt' + $index" ng-model="COL_FIELD" ng-input="COL_FIELD" data-placeholder="-- Select One --" 
>


</select>


Live code: http://plnkr.co/edit/IOBXNy2hcJWbtMXZS3SO?p=preview