Custom x-editable alike AngularJS Directive
Custom AngularJS inline-editing directive which in contrast to x-editable, conceals the original text.
by Ahmad Baktash Hayeri
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<div ng-controller="Controller as ctrl">
<table class="table table-bordered table-condensed table-striped table-responsive">
<tr>
<th>#</th>
<th>Name</th>
<th>Action</th>
</tr>
<tr ng-repeat="user in ctrl.users">
<td>{{ $index + 1 }}</td>
<td>
<a href="#" my-editable-text="user.name">{{ user }}</a>
</td>
<td><button class="btn btn-sm btn-default" ng-click="ctrl.deleteUser(user)"><span class="glyphicon glyphicon-trash"></span></button></td>
</tr>
</table>
<span class="input-group">
<input class="input-sm form-control" ng-model="ctrl.user" />
<span class="input-group-btn">
<button class="btn btn-sm btn-default" ng-click="ctrl.addUser()">
Add User
</button>
</span>
</span>
<pre>{{ ctrl.users | json }}</pre>
</div>
CSS
body {
padding: 1.5rem;
}
JavaScript
angular.module('app', [])
.controller('Controller', function() {
this.users = [{
name: "Stroustrup"
}, {
name: "Linus Torvalds"
}, {
name: "James Gosling"
}];
this.user = "Somebody";
this.addUser = function() {
var self = this;
this.users.push({
name: self.user
});
};
this.deleteUser = function(user){
var self = this;
self.users.splice(user, 1);
};
})
.directive('myEditableText', function() {
return {
scope: {
myEditableText: '='
},
template: "<span ng-hide='editMode'>{{ myEditableText }}</span><form ng-show='editMode'><span class='input-group'><input class='input-sm form-control' name='editable' type='text' ng-model='model'><span class='input-group-btn'><button ng-click='vm.commitChanges()' class='btn btn-sm btn-success'>Save</button><button class='btn btn-sm btn-danger' ng-click='vm.cancelChanges()'>Cancel</button></span></form>",
controller: function($scope, $timeout) {
$scope.model = angular.copy($scope.myEditableText);
$scope.editMode = false;
this.commitChanges = function() {
$timeout(function() {
$scope.editMode = false;
$scope.myEditableText = $scope.model;
});
};
this.cancelChanges = function() {
$timeout(function() {
$scope.editMode = false;
});
}
},
controllerAs: 'vm',
link: function(scope, iElement, attrs, ctrl) {
iElement.on('click', function() {
scope.editMode = true;
scope.$apply();
});
}
};
})