【问题标题】:Custom directive scope vs attrs自定义指令范围与 attrs
【发布时间】:2015-06-22 19:47:10
【问题描述】:

在 Angular 中创建自定义指令时,我有一个担忧。 当我使用链接函数时,我不确定使用 attrs 或范围访问属性时的真正区别是什么。 以这段代码为例:

myApp.directive('someDirective', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            title: '=title'
        },
        template: '<img/>',
        link: function(scope, element, attrs) {
            if (scope.title) {
                // do something here
            }
            if (attrs.title){
                // do something here
            }
        },
    }

根据我的观察,从 attrs 和按范围访问“title”属性具有类似的效果。真正的区别是什么?

【问题讨论】:

标签: javascript angularjs angularjs-directive


【解决方案1】:

不同之处在于,根据定义,属性是字符串类型。总是。在您的情况下,attrs.title 将是字符串,等于您在 HTML 中传递给属性的任何内容。

但是,scope.title 是属性 attr.title 的解析和评估结果。

例如。如果你在 HTML 中使用这样的东西

<some-directive title="name"></some-directive>

其中$scope.name = "Thomas Mann" 定义在范围内,那么attr.title 将是字符串"name",而scope.title 将是"Thomas Mann"

【讨论】:

  • 很棒的答案。除此之外,您还可以使用scope.$eval(attrs.title) 来获取作用域上下文中属性的解析版本。
  • 仅此而已?我认为当您使用 @ 绑定范围时,它也被作为字符串传递,所以它具有相同的效果,对吧?
  • @Marcin86,传递给属性的东西几乎是字符串,而作为范围变量传递的东西可以是任何数据类型。但您也可以使用scope.$eval(attrs.title) 来评估范围上下文中的属性,正如我在上面评论的那样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-09
  • 1970-01-01
  • 1970-01-01
  • 2015-08-20
  • 1970-01-01
  • 2015-09-20
相关资源
最近更新 更多