2017-11-06 12 views
0

ボタンをクリックするとコンテンツ編集可能なdivを追加します。オンラインリソースでは、私はそのための指令を作成しなければならないと言います。私が試してみました。ここではここコンテンツをクリックすると編集可能なdivが表示されます

app..directive("addEditableDiv", function($compile){ 
    return{ 
    restrict: 'A', 
    require: "ngModel", 
    link: function(scope , element){   
     element.bind("click", function(e){ 

     var childNode = $compile('<div ng-click="addDiv()" > here</div>')(scope) 
     element.parent().append(childNode); 

     }); 

     scope.addDiv = function(scope , element , attrs , ngModel){ 

       function read() { 
        ngModel.$setViewValue(element.html()); 
        ngModel.$render = function(){ 
        element.html(ngModel.$viewValue || ""); 
        }; 

        element.bind("click to write", function(){ 
        scope.$apply(read); 
        }) 

       } 
       } 
    } 
} 
}) 

答えて

1

が機能していない次のコードは、コンテンツの編集可能なdivのための作業のコードは、されている:(あなたはまた、この機能のためのライブラリを使用することができます)

var app = angular.module("MyApp", []) 
 
    .controller('Controller', function($scope) { 
 
    $scope.totalEditableDiv = []; 
 
    $scope.addDiv = function() { 
 
     $scope.totalEditableDiv.push($scope.totalEditableDiv.length); 
 
    } 
 
    $scope.addDiv(); 
 
    }) 
 
app.directive("contenteditable", function() { 
 
    return { 
 
    restrict: "A", 
 
    require: "ngModel", 
 
    link: function(scope, element, attrs, ngModel) { 
 

 
     function read() { 
 
     ngModel.$setViewValue(element.html()); 
 
     } 
 

 
     ngModel.$render = function() { 
 
     element.html(ngModel.$viewValue || ""); 
 
     }; 
 

 
     element.bind("blur keyup change", function() { 
 
     scope.$apply(read); 
 
     }); 
 
    } 
 
    }; 
 
});
[contenteditable] { 
 
    border: 2px dotted #ccc; 
 
    background-color: #eee; 
 
    padding: 2px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<body ng-app="MyApp"> 
 
    <div ng-controller="Controller"> 
 

 
    <div ng-repeat="editableDiv in totalEditableDiv"> 
 
     <div contenteditable ng-model="text[$index]"></div> 
 
     <br> 
 

 
     <b>Source of the Div:</b> 
 
     <p style="border:1px solid green;padding:15px;">{{text[$index]}}</p> 
 
    </div> 
 
    <button ng-click="addDiv()" style="color:blue">Add More</button> 
 
    </div> 
 
</body>

+0

感謝私はそれを実際に持っています。私が必要とするのは、そのコンテンツを編集可能なdivを追加するボタンをクリックすることです。 – TheTechGuy

+0

@ICodeあなたの要件に従って私の答えを更新しました。 –

+0

ありがとう – TheTechGuy

関連する問題