Skip to content

Instantly share code, notes, and snippets.

@shlomiassaf
Last active August 29, 2015 14:04
Show Gist options
  • Save shlomiassaf/7485c61ecb464f261194 to your computer and use it in GitHub Desktop.
Save shlomiassaf/7485c61ecb464f261194 to your computer and use it in GitHub Desktop.
Dynamic cell editable flag for Angular UI ng-grid using a decorator.
app.config(function($provide) {
$provide.decorator('ngCellHasFocusDirective', function($delegate) {
var directive = $delegate[0];
var original = directive.compile;
directive.compile = function(element, attrs) {
return function($scope, element) {
// state.
var isOn = false;
function setElement() {
// support dynamic columnDef and return flag value.
if ( angular.isFunction($scope.col.colDef.enableCellEditDynamic) && ! $scope.col.colDef.enableCellEditDynamic($scope) ) {
isOn = false;
element.off();
}
else if( !isOn ) {
isOn = true; // prevent a useless call
return original()($scope, element);
}
}
// Were on the cell scope, 'ngGridEventEndCellEdit' will fire from this scope (up & down, see 'ng-cell-has-focus.js').
// Since a row is a well known cell brotherhood all fellow cell-scopes will not fire on this event. (only row scope and up...)
// hence we need to make a connection either via $watch and a common watched or by scope comm, I used scope comm...
// When using $watch make sure to fire up digest on a scope listened by all cell scopes.
$scope.$on('ngGridEventEndCellEdit', function() {
$scope.$parent.$broadcast('ngGridEventDynamicCanEditCell');
});
$scope.$on('ngGridEventDynamicCanEditCell', function() {
setElement();
});
return setElement(); // original()($scope, element);
};
};
return $delegate;
});
});
@shlomiassaf
Copy link
Author

A simple decorator to ng-grid (https://github.com/angular-ui/ng-grid) that add`s support for dynamic Enable Cell Edit (enableCellEdit) rule via column definition object (columnDef).

Usage example: In every row, for field X, if value of field Y is negative dont allow editing of field X.

scope.gridOptions = {
    columnDefs: [
        {
            field:'X',
            displayName:'ColumnX',
            enableCellEdit: true,
            enableCellEditDynamic: function(scope) {
                if ( scope.row.entity.X < 0 ) {
                    return false;
                }
                return true;
             }
         },
        {
            field:'Y',
            displayName:'ColumnY',
            enableCellEdit: true
         }
    ]
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment