【问题标题】:AngularJS - Is it possible to pass attr value in Directive link function directly to template?AngularJS - 是否可以将指令链接函数中的 attr 值直接传递给模板?
【发布时间】:2015-07-28 08:05:53
【问题描述】:

我想知道是否可以直接在模板配置中访问传递给自定义指令的属性?所以像这样的东西......目前不起作用?

angular.module('msDirectives', [])
    .directive('msPerson', function(){
        return{
            restrict: 'E',
            link: function(scope, element, attrs){
            },
            template: '<h1>{{attrs.firstName}}</h1>',
        };
    });

我意识到我可以将 attrs.firstName 分配给链接函数中的范围以使其工作(如下所示),只是试图了解范围是否是模板中唯一可访问的东西,或者 attrs 是否也传递给它.

angular.module('msDirectives', [])
    .directive('msPerson', function(){
        return{
            restrict: 'E',
            link: function(scope, element, attrs){
                scope.name = attrs.firstName;
            },
            template: '<h1>{{name}}</h1>'
        };
    });

【问题讨论】:

  • 你总是可以做到scope.attrs = attrs。
  • 这是否意味着作用域是唯一传递给模板的瘦身。 attrs 永远不会自动传递给模板?
  • Angular 表达式和指令(在模板中或其他地方)总是链接到某个范围 - 没有别的。然后,您可以绑定范围的属性。某些属性会自动在作用域上设置,例如 ControllerAs 中的别名,或者某些库/指令可能会传递一些“本地”……但归根结底,它只是作用域的一个属性。具体来说,$scope.attrs 不会自动设置。

标签: angularjs angularjs-directive angularjs-scope


【解决方案1】:

隔离作用域的目的(除了隔离本身)是将属性值分配给作用域。

angular.module('msDirectives', [])
    .directive('msPerson', function(){
        return{
            restrict: 'E',
            scope: {
                name: '@firstName'
            },
            template: '<h1>{{name}}</h1>'
        };
    });

【讨论】:

  • 这是否意味着作用域是唯一传递给模板的瘦身。 attrs 永远不会自动传递给模板?
  • 是的,你是对的,就是这样。最常见的方法是通过隔离作用域,您必须手动将 attrs 中的属性值分配给控制器/链接中的作用域(如果由于某种原因您不能使用隔离作用域)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多