2013-08-29 119 views
0

我有一个带占位符的contenteditable指令,它基于Craig Stuntz's javascript contenteditable placeholder。该指令做以下工作将div文本传递给angularjs指令

  1. 检查DIV的textContent存在,如果存在隐藏占位否则显示占位
  2. 如果用户注重CONTENTEDITABLE然后隐藏占位

但是我有一个已经提到的一个问题由Craig特技

If you update the div text in JavaScript (instead of just typing into the div on the page), no events are fired, and you must let the plugin know that you've changed the contents by triggering the change event.

我不知道往哪里放.triggerHandler('change')以及该指令如何知道来自javascript的div文本是否为空或不为空?

下面是代码

app.directive("contenteditable", function() { 
return { 
    require: 'ngModel', 
    link: function(scope, element, attrs, ctrl) { 
     // view -> model 
    element.bind('input', function() { 
    scope.$apply(function() { 
     ctrl.$setViewValue(element.text()); 
    }); 

    if (this.textContent) { 
      this.setAttribute('data-contenteditable-placeholder', 'true'); 
      console.log(this); 
     } else { 
     this.removeAttribute('data-contenteditable-placeholder'); 
     } 
    }); 
    // model -> view 
    //ctrl.$render = function() { 
    // element.text(ctrl.$viewValue); 
    //}; 
    //ctrl.$setViewValue(element.text()); 
    } 
} 
}); 

CSS

*[data-placeholder]:not(:focus):not([data-contenteditable-placeholder])::before { 
    content: attr(data-placeholder); 
    margin-left: 2px; 
    color: #b3b3b3; 
} 

div[contenteditable]:focus{ 
    outline: none; 
} 
+0

你有可能发布最终解决方案吗? – chris

回答

1

我相信你是几乎没有。

您只需'watch'输入字段的值,以便您可以触发您的.triggerHandler('change')事件。

该指令应该监视()您的模型的变化,手表回调应该1 - 检查div是否为空,2 - 调用触发事件(或任何DOM操作) - 您可以看到下面的伪代码。

scope.$watch('yourViewModel', function(newValue, oldValue) { 

// here you check if the newValue is empty 

// depending on the check above you call (or not) triggerHandler('change') 

}); 

你可以看到scope.$watch的第二个参数是接收newValue和模型的oldValue,这样你就可以在该函数内部测试,如果newValue是空的函数(因此检查,如果股利文本空)。

希望能够帮助或至少让您指向正确的方向。

相关问题