最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Custom directive scope vs attrs - Stack Overflow

programmeradmin5浏览0评论

I have one concern when creating a custom directive in angular. When I'm using a link function, I'm not sure what is the real difference when accessing attributes with attrs or scope. Take this piece of code for example:

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
            }
        },
    }

From my observations accessing 'title' attribute from attrs and by scope has a similar effect. What is the real difference?

I have one concern when creating a custom directive in angular. When I'm using a link function, I'm not sure what is the real difference when accessing attributes with attrs or scope. Take this piece of code for example:

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
            }
        },
    }

From my observations accessing 'title' attribute from attrs and by scope has a similar effect. What is the real difference?

Share Improve this question edited Oct 2, 2017 at 23:23 NOCARRIER 2,6345 gold badges42 silver badges62 bronze badges asked Jun 22, 2015 at 19:47 Marcin86Marcin86 1312 silver badges9 bronze badges 1
  • Please look at this stackoverflow./questions/14300986/… – michelem Commented Jun 22, 2015 at 19:53
Add a ment  | 

1 Answer 1

Reset to default 20

The difference is that attribute is of a String type by definition. Always. In your case attrs.title will be literally string equal to whatever you pass into attribute in HTML.

However, scope.title is parsed and evaluated result of the attribute attr.title.

Ex. If you use something like this in HTML

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

where $scope.name = "Thomas Mann" defined in the scope, then attr.title will be string "name", while scope.title will be "Thomas Mann".

发布评论

评论列表(0)

  1. 暂无评论