2017-01-13 19 views
1

我想編輯和保存選定指令中的內容。指令由ng-repeat填充。在按鈕點擊可見的項目應更改爲輸入字段,並再次單擊它應該扭轉如何使用角度js中的指令切換編輯和保存

指令是

.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

問題是點擊所有指令更改爲可編輯的,反之亦然。 如何使它在選定的指令集上工作

回答

1

請嘗試如下所示。使用帶有指令的template要比直接修改html要簡單得多。

指令

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> 

我叉你plunker here