指令模板中的数据绑定 [英] Data-binding in a directive template

查看:26
本文介绍了指令模板中的数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个非常基本的Angular 指令,它生成一个div",它可以有两种状态:on"和off".

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.

这里是 Angular 指令定义:

Here is the Angular directive definition:

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...?

此外,在设计方面,是采用Angular 方式"还是有更好的做法?

Moreover, in term of design, am doing it the "Angular way" or is there better practices?

感谢您的任何意见.:)

Thanks for any input. :)

最终

感谢 MarkBertrandJames 的投入:

Thanks to Mark, Bertrand and James for their input:

  • 您必须在更新isOn"属性后调用 scope.$apply() 以使 Angular 了解其更改(考虑一下,这也是它在其他框架中的工作方式,例如具有 INotifyPropertyChanged 接口的 WPF/Silverlight,但不是在具有所有魔法绑定的 Flex 中)或使用 ng-click 就像 Bertrand 建议的那样
  • 您必须为每个 CSS 类提供ng-class"条件
  • 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-click 指令来更改 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆