Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to provide a default value for an isolated scope alias?

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.

like image 767
dnc253 Avatar asked Sep 28 '12 19:09

dnc253


People also ask

What is default scope value?

If no value is specified for scope , page scope is the default unless otherwise specified. In other words, the default is page , i.e. the current JSP page.

What is the default scope in an angular directive?

By default, directives do not create their own scope; instead they use the scope of their parent, generally a controller (within the scope of which the directive is defined). We can change the default scope of the directive using the scope field of the DDO (Data Definition Object).

What is attrs in AngularJS?

Using attrs you are able to access the attributes defined in your html tag like <fm-rating ng-model="$parent.restaurant.price" symbol="$" readonly="true"> So in this case you will have access to the symbol and readonly attributes.

How to destroy directive AngularJS?

You can use element. on('$destroy', ...) or scope. $on('$destroy', ...) to run a clean-up function when the directive is removed.


1 Answers

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";
    }
    ...
  }
like image 156
Niall Smart Avatar answered Oct 05 '22 09:10

Niall Smart