Sco*_*ord 4 jquery angularjs angular-ui
情况: 我正在移植,或者我应该说尝试将Lakshan Perera的简单jQuery ColorPicker(https://github.com/laktek/really-simple-color-picker)移植到Angular.在回顾SO上的类似问题后,似乎有些人通过控制器分配了插件的范围,但正确的(Angular)方法是将插件包装在指令中.我越来越近了.我能够通过我的新自定义属性在我的视图中正确呈现插件,但我不确定如何设置指令以将输入值传递给属性的值(ng-model).实际的输入更新,但Angular没有监听更改,因此实际上并不知道输入值已更新.官方文档讨论了如何设置自定义属性(http://docs.angularjs.org/guide/directive),
期望的功能 -
<input my-widget="{{color}}" type="text"/> <!-- my-widget instantiates my directive -->
<h1 style="color:{{color}}"></h1> <!-- I would like the input value to dump into the attribute's value, in this case {{color}} -->
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止:
app.directive('myWidget', function(){
var myLink = function(scope, element, attr) {
scope.$watch('element',function(){
var value = element.val();
element.change(function(){
console.log(attr.ngModel); // This is currently logging undefined
// Push value to attr here?
console.log( value + ' was selected');
});
});
var element = $(element).colorPicker();
}
return {
restrict:'A',
link: myLink
}
});
Run Code Online (Sandbox Code Playgroud)
问题: 如何设置属性值以捕获元素的更新值?
我会像这样实现它:
app.directive('colorPicker', function() {
return {
scope: {
color: '=colorPicker'
},
link: function(scope, element, attrs) {
element.colorPicker({
// initialize the color to the color on the scope
pickerDefault: scope.color,
// update the scope whenever we pick a new color
onColorChange: function(id, newValue) {
scope.$apply(function() {
scope.color = newValue;
});
}
});
// update the color picker whenever the value on the scope changes
scope.$watch('color', function(value) {
element.val(value);
element.change();
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
你会这样使用它:
<input color-picker="color">
Run Code Online (Sandbox Code Playgroud)
这是一个工作的jsFiddle,有几个小小的玩具:http://jsfiddle.net/BinaryMuse/x2uwQ/
jsFiddle使用隔离范围将范围值绑定color到传递给color-picker属性的任何内容.我们$watch在表达式'color'中查看此值何时更改,并相应地更新颜色选择器.
| 归档时间: |
|
| 查看次数: |
3576 次 |
| 最近记录: |