When do isolated scope properties actually get added to the scope?

后端 未结 2 529
小蘑菇
小蘑菇 2021-01-19 12:00

I\'m creating some directives with an isolated scope and some aliased properties. For example:

scope: {
   prop1: \'@\'
}

My question is, w

相关标签:
2条回答
  • 2021-01-19 12:28

    Here's my understanding: In general in a directive, you can not assume that any variable in a scope is defined or has a stable value. You need to $watch anything that's of interest to you.

    Think of ng-repeat - the thing that you're repeating on might not exist at link time, it might change often, etc. - it's up to the directive to handle those scenarios.

    Now I know that doesn't answer your question - you're creating an isolated scope which is explicitly setting a scope value, so intuitively what you're doing is different than the ng-repeat example. But it looks like Angular treats them the same and this is probably a good thing.

    Depending on what you need to use the attribute for I think you can solve your problem in two ways:

    1. If it's an evaluated value and it might change, wrap it in a watch so you can react.
    2. If it's a static value you can use attrs.prop1 and pull it down at the beginning of your link fn.

    Both of these options I've added to the fiddle here.

    0 讨论(0)
  • 2021-01-19 12:39

    I found that this works inside the directive definition:

    scope: {
        prop1: '@'
    },
    link: function(scope, element, attrs) {
        ...
        attrs.$observe('prop1', function(val) { 
            scope.prop1 = val || 'default'
        });
        ...
    }
    

    to make

    <div my-directive></div>
    

    behave like

    <div my-directive prop1="default"></div>
    
    0 讨论(0)
提交回复
热议问题