在指令模板的数据绑定 [英] Data-binding in a directive template
问题描述
我想建立一个真正的基本的角指令生成一个格,可以有两种状态:开和关
I'm trying to build a really basic Angular directive that generates a "div" that can have two states: "on" and "off".
我有天真地拿出,你可以在这里找到一个实现: http://jsfiddle.net/wSz2f/
I've naively come up with an implementation that you can find here: http://jsfiddle.net/wSz2f/
初始显示是正确的,但在可视状态不更新范围的状态发生变化时。
The initial display is correct but the visual state is not updated when the scope state changes.
下面是角指令定义:
var test = angular.module("test", []);
test.directive("led", function()
{
return {
restrict: "E",
replace: true,
template: "<div class='led led-off' ng-class='{ \"led-on\": isOn }'>{{isOn}}</div>",
link: function(scope, element, attributes, controller)
{
scope.isOn = false;
element.bind("click", function()
{
scope.isOn = !scope.isOn;
});
}
};
});
我想我做一些愚蠢的,但什么...?
I guess I'm doing something stupid but what...?
此外,在设计来看,我这样做了角办法还是有更好的做法?
Moreover, in term of design, am doing it the "Angular way" or is there better practices?
感谢您的任何输入。 :)
Thanks for any input. :)
最后编辑:
感谢的标记的伯特兰的和的詹姆斯的征求他们的意见:
Thanks to Mark, Bertrand and James for their input:
- 您必须要么调用 范围。$适用()的更新ISON属性,以使后的角了解它的变化(想着它,这是它如何工作太像INotifyPropertyChanged接口WPF / Silverlight的其他框架,而不是在Flex中其所有的魔法绑定)或使用 NG-点击像的伯特兰建议的
- 您必须提供纳克级为每个CSS类的条件
- you have to either call scope.$apply() after updating the "isOn" property to make Angular aware of its change (thinking about it this is how it works too in other frameworks like WPF/Silverlight with the INotifyPropertyChanged interface, but not in Flex with all its magic binding) or use ng-click like suggested by Bertrand
- you have to provide "ng-class" a condition for each CSS class
推荐答案
在你的情况,你不得不解雇摘要
In your case you have to fire the digest
element.bind("click", function()
{
scope.isOn = !scope.isOn;
scope.$apply();
});
甚至更好,你可以使用NG-点击指令在模板中改变ISON的状态。
or even better, you could use the ng-click directive in your template to change the state of isOn.
var test = angular.module("test", []);
test.directive("led", function()
{
return {
restrict: "E",
replace: true,
template: "<div class='led led-off' ng-class='{ \"led-on\": isOn, \"led-off\": !isOn }' ng-click='onOff()'>{{isOn}}</div>",
link: function(scope, element, attributes, controller)
{
scope.isOn = false;
scope.onOff = function () {
scope.isOn = !scope.isOn;
}
}
};
});
下面是一个小提琴
这篇关于在指令模板的数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!