2015-09-28 21 views
0

CONTENTEDITABLE格值我有一個CONTENTEDITABLE DIV這樣的:獲取角

<div contenteditable="true" ng-model="name">{{ name }}</div> 
<input type="button" ng-click="checkScope()" value="Click me"> 

在我的控制器:

var app = angular.module('sbAdminApp', []); 
app.controller('MyCtrl', function($scope) { 
    $scope.name = 'Adrian'; 

    $scope.checkScope = function(){ 
     console.log($scope.name); 
    } 
}); 

我如何使用範圍,當我點擊獲得CONTENTEDITABLE div的最新值按鈕?

回答

3

你需要一個指令來解決這個

app.directive('contenteditable', [function() { 
    return { 
     require: '?ngModel', 
     scope: { 

     }, 
     link: function(scope, element, attrs, ctrl) { 
      // view -> model (when div gets blur update the view value of the model) 
      element.bind('blur', function() { 
       scope.$apply(function() { 
        ctrl.$setViewValue(element.html()); 
       }); 
      }); 

      // model -> view 
      ctrl.$render = function() { 
       element.html(ctrl.$viewValue); 
      }; 

      // load init value from DOM 
      ctrl.$render(); 

      // remove the attached events to element when destroying the scope 
      scope.$on('$destroy', function() { 
       element.unbind('blur'); 
       element.unbind('paste'); 
       element.unbind('focus'); 
      }); 
     } 
    }; 
}]); 

,你可以用它像這樣

<div contenteditable="true" ng-model="name">{{ name }}</div> 

這裏是一個demo

+0

我想更新的範圍值,所以怎麼能我在element.bind函數中獲得當前可編輯的div範圍(如當前情況下的「名稱」)。 – Rahul

+0

指令正在更新'$ scope.name'屬性 –

+0

好極了,我會錯誤的方向..感謝您的最後評論。 +1 – Rahul