2

Should a directive be used in AngularJS to implement a widget or a controller/service? When talking about a widget I'm thinking of a UI control that you would interact with from a controller e.g. dialog, tree, grid, chart.

For example if I was to create a Dialog widget I would want to call a show() function on the widget to display the dialog. This doesn't seem to be possible using directives. I've seen a variable used, e.g. 'showDialog', on the root scope that the directive watches to work around this. In angular-ui they use a service to implement the dialog.

2 Answers 2

2

Yes, a directive can do this, you can use two way binding to pass in the expression you want to use to determine if the HTML is visible or not.

Adjust your thinking: Instead of a "UI control that you would interact with from a controller" think MVC, introduce a 'model'. The controller can change the model by setting values on the scope, the view handles what HTML to show for a given model. The controller should not interact with the HTML by manipulating the DOM directly.

In the markup you might have:

          <modal-dialog show="showPopup">

where showPopup is a current scope variable (or an expression).

In your directive you would create an isolated scope and use '=' for the 'show' parameter.

In your directive's HTML template you would use the 'show' value to reveal the dialog.

Of course in this case there's an easier way ... ng-show already does this for you so you can just use that directive mixed in with your own modal-dialog directive that includes the template you want to show.

          <modal-dialog ng-show="showPopup">
Sign up to request clarification or add additional context in comments.

1 Comment

I ended up using a service to create the dialog as it was much easier to use existing code this way. This could work but I didn't have the time to give it a fair go.
1

Mostly, Directives use as template for HTML view.

Directive prevents code duplicate and makes your HTML more clearer and easy maintenance.

As I know you must create tag or class like "pointer" to bind directive with DOM.

According to Dialog implementation that use template, you can use service only and separate controller.

Take a look on this description.

You can't implement Dialog in directive.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.