如何将指令的属性绑定到Angular.js中的下拉列表?

时间:2012-10-23 14:39:49

标签: javascript angularjs

我在$ scope.templates的下拉列表中有一系列模板:

[{"id":1, "name":"Test 1",{"id":2, "name":"Test 2"}]

我也有一个指令,

<editor data-template="1"></editor>

根据下拉列表中选择的模板,它应该使用适当的模板重新呈现指令。这可能吗?到目前为止,我只看到字段与div的简单一对一数据绑定,并且没有触发重新呈现整个指令。这种情况的最佳方法是什么?

更新:指令$ scope更基本,是跨控制器双向绑定。例如我似乎无法弄清楚如何使服务对象在控制器之间保持同步。我真正想要发生的是一个控制器的变化可供另一个控制器使用,反之亦然。 http://jsfiddle.net/9gSVn/1/

1 个答案:

答案 0 :(得分:1)

一种方法是创建一个指令,在范围值更改时替换html内容。 This blog post非常有助于描述使用动态模板创建指令的步骤。

带有指示模型更改的指令的

Here is a sample fiddle

module.directive('template', function () {
    var getTemplate = function (id) {
        var template = '<div>no template for ' + id + '</div>';

        switch (id) {
            case 1:
                template = '<div>template 1 from directive</div>';
                break;
            case 2:
                template = '<div>template 2 also from directive</div>';
                break;
        }

        return template;
    }
    return {
        restrict: 'E',
        replace: true,
        scope: { id: '=templateId' },
        link: function (scope, element, attrs) {
            scope.$watch('id', function (newValue, oldValue) {
                element.html(getTemplate(newValue));
            });
        }
    };
});