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

javascript - Is there any way to provide a default value for an isolated scope alias? - Stack Overflow

programmeradmin4浏览0评论

Say I have the following as part of my directive definition:

scope: {
    prop1: '@'
}

Is there any way for prop1 to get a default value if the directive doesn't have a prop1 attribute? Sure, I can check if it is defined myself and set it, but the property isn't always set when you would expect. I'm just wondering if there is any syntax I missed in the documentation, or if there is a good standard way of doing this. Thanks.

Say I have the following as part of my directive definition:

scope: {
    prop1: '@'
}

Is there any way for prop1 to get a default value if the directive doesn't have a prop1 attribute? Sure, I can check if it is defined myself and set it, but the property isn't always set when you would expect. I'm just wondering if there is any syntax I missed in the documentation, or if there is a good standard way of doing this. Thanks.

Share Improve this question edited May 23, 2017 at 12:02 CommunityBot 11 silver badge asked Sep 28, 2012 at 19:44 dnc253dnc253 40.3k41 gold badges144 silver badges160 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 19

It depends on what default value you want to assign. If you want to default to a name in the parent scope, setting a default attribute value in the directive's compile function will work:

  compile: function(element, attrs) {
    if (attrs.person == undefined) {
      attrs.$set("person", "person");
    }
  ...

If you want the directive to provide the default value, it gets a little tricker as Angular will not let you assign to the alias in the isolate scope (you will get a "Non-assignable model expression" exception from the watcher that's trying to propagate the assignment to the isolated parent scope). However you can prevent this by marking the attribute as optional (which means Angular won't register the listener when the property is ommited).

  scope: {
    person: "=?"
  },
  link: function(scope, element, attrs) {
    if (scope.person == undefined) {
      scope.person = "Bob";
    }
    ...
  }
scope['prop1'] = scope['prop1'] || '@'
发布评论

评论列表(0)

  1. 暂无评论