Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directive scope attributes without an isolated scope in AngularJS

Tags:

Is there a way of inheriting the parent scope while extending it with passed attributes?

I want to pass parameters to a reusable directive directly from the template without having to alter the DOM in the linking function.

For example:

<form-input icon="icon-email" label="email" ng-model="data.input"></form-input> 

For a directive like this:

    <div class="form-group">       <label>{{label}}</label>       <div class="input-group">         <div class="{{icon}}">@</div>         <input class="form-control" placeholder="Email" ng-model="mail.email">       </div>     </div> 

ng-model is in the parent scope, controlling an entire form in this case, but I don't think it's necessary to store styling attributes in the controller.

Is there a way of passing parameters directly in the template without creating an isolate scope?

like image 628
BarakChamo Avatar asked Jul 09 '14 10:07

BarakChamo


People also ask

What are the directive scopes in AngularJS?

The directive scope uses prefixes to achieve that. Using prefixes helps establish a two-way or one-way binding between parent and directive scopes, and also make calls to parent scope methods. To access any data in the parent scope requires passing the data at two places – the directive scope and the directive tag.

What is isolated scope in AngularJS?

Isolated scope directive is a scope that does not inherit from the parent and exist on its own. Scenario: Lets create a very simple directive which will show the object from the parent controller.

What is the default scope type in AngularJS?

Scopes in AngularJS Directives There are 3 main ways in which scope can be passed to the directive from the invoking view (HTML): Default Scope. Inherited Scope. Isolated Scope.

Can we use multiple directives in AngularJS?

... is quite illustrative as AngularJS doesn't allow multiple directives (on the same DOM level) to create their own isolate scopes. According to the documentation, this restriction is imposed in order to prevent collision or unsupported configuration of the $scope objects.


1 Answers

You would not be able to 'extend' the parent scope as such. However your objective can be accomplished by utilizing the directive tag attributes that are injected in the link function of your directive.

So eg. for attaching your label variable, your directive's link function would look like below:

 link: function ($scope, $element, $attributes) {          $scope.label = $scope.$eval($attributes.label);         } 


You can check out the below plunker for a live demo.
http://plnkr.co/edit/2qMgJSSlDyU6VwdUoYB7?p=preview

like image 197
Angad Avatar answered Sep 30 '22 05:09

Angad