Deep 3015
Deep 3015

Reputation: 10075

How to toggle edit and save using directive in angular js

I want to edit and save content in selected directive.The directive is populated by ng-repeat. On button click visible items should change to input field and again on click it should reverse

Directive is

.directive('component', function() {
  var link = function(scope, element, attrs) {
    var render = function() {
      var t = scope.layouts[scope.type][attrs.indexs];
      var icon = scope.layouts[scope.type][attrs.indexs];
      var v = attrs.value;
      if(scope.type=="edit"){
        element.html('<input type="' + t + '" ng-model="vm.name" value="'+v+'">');
      if(attrs.indexs==1){
        element.html('<' + t + '>Save');
      }}
      if(scope.type=="display"){
        element.html('<' + t + ' ng-model="'+v+'" >'+v+'</'+t+'>');
      if(attrs.indexs==1){
        element.html('<' + t + ' >Edit');
      }}};
    scope.$watch('type', function(newValue, oldValue) {
      render();
    });

  };
  return {
    restrict : 'E',
    link : link
  }
});

plunker Link

Problem is on click all directive is changed to editable and vice-versa. How can I make it work on selected set of directive

Upvotes: 2

Views: 1779

Answers (1)

Michael Sacket
Michael Sacket

Reputation: 907

Try something like the following. It's much simpler to use a template with a directive than trying to modify the html directly.

Directive

angular.module('myApp', [])
.controller('MyController', MyController)
.directive('component', function(){
      return {
         template: [
           '<div>',
           '<span style="font-weight:bold" ng-show="!editing">{{ value }} <button ng-click="editing = true">Edit</button></span>',
           '<span ng-show="editing"><input type="input" ng-model="value"><button ng-click="editing = false">Save</button></span>',
           '</div>'  
         ].join(''),
         restrict: 'E',
         scope: {
            value: '=value'
         },
         link: function($scope){
             $scope.editing = false;
         }
      }
});

HTML

<div class="col-sm-12" ng-repeat="s in vm.allCat track by $index">
    <div class="col-sm-1 text-muted">Name</div>
    <div class="col-sm-9 text-left">
        <component value="s.name"></component>
    </div>
    </div>
</div>

I've forked your plunker here.

Upvotes: 2

Related Questions