【问题标题】:Angular JS directive, change a 2 way data binding in the link functionAngular JS 指令,更改链接函数中的 2 路数据绑定
【发布时间】:2014-05-05 02:42:39
【问题描述】:

我正在尝试创建一个角度指令,我可以在其中通过单个选项对象或通过某些属性设置选项。以下是此类代码的示例:

app.directive('testElement', [function () {
    return {
        restrict: "E",
        scope: {
            options: "="
        },
        template: "<p><span>Name: </span>{{ options.name }}</p>",
        link: function (scope, element, attrs) {
            scope.options = scope.options || {};
            if (attrs.name)
                scope.options.name = attrs.name;
        }
    };
}]);

这很好用,因为如果我通过选项属性传入名称,则会显示名称值。但是如果我通过 name 属性传递一个名称,即使链接函数确实修改了选项,该值也不会呈现。

http://plnkr.co/edit/IMVZRdAW2a5HvSq2WtgT?p=preview

我觉得我在选项的 2 路数据绑定如何工作方面缺少一些基本知识。

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    如果不通过双向数据绑定,angular会生气:

    https://github.com/angular/angular.js/issues/1435

    使用可选绑定 (=?):

    app.directive('testElement', [function () {
        return {
            restrict: "E",
            scope: {
                options: "=?"
            },
            template: "<p><span>Name: </span>{{ options.name }}{{ test }}</p>",
            link: function (scope, element, attrs) {
                scope.options = scope.options || {};
                if (attrs.name)
                    scope.options.name = attrs.name;
            }
        };
    }]);
    

    或者,如果您使用的是旧版本的 angular,请在 attrs 上使用 $eval。选项:

    app.directive('testElement', [function () {
        return {
            restrict: "E",
            //Still can create isolate scope to not clobber parent scope variables.
            scope: {},
            template: "<p><span>Name: </span>{{ options.name }}{{ test }}</p>",
            link: function (scope, element, attrs) {
                scope.options = scope.$eval(attrs.options) || {};
                if (attrs.name)
                    scope.options.name = attrs.name;
            }
        };
    }]);
    

    【讨论】:

    • 你可以用=?,看我的回答
    • 当使用可选的双重绑定时,该值永远不会被传递(v1.3.10)。范围:{ selectedValue:'=?selectedValue' }。移除 ? 时有效。知道这是怎么发生的吗?
    【解决方案2】:

    该指令需要一个选项参数。在第二种情况下,您没有提供它,因此出现错误

    如果隔离范围变量是可选的,请使用 ? 之类的

     scope: {
                options: "=?"
            }
    

    见我的 plunkr http://plnkr.co/edit/eGh6r1X7HzY1sZIDYZ69?p=preview

    这里有关于隔离范围的文档http://docs.angularjs.org/api/ng/service/$compile

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-14
      • 2015-06-24
      • 2017-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-28
      相关资源
      最近更新 更多