Marc Canals Giraut
Marc Canals Giraut

Reputation: 354

Directives is the best way to inject html with angularjs

I would like to add a piece of code in all my views to show a notification bar in the top in order to inform to the user.

I'm trying to do that with a directive. Check this simple sample out: http://jsfiddle.net/dirkom/wsrb6/2/

HTML:

    <bca-notification></bca-notification>

Directive:

.directive('bcaNotification', function () {
    var notification = '<div id="notification"  ng-init="showThis=true" ng-show="showThis">' +
                        'Error message<a id="close" ng-click="showThis = false">Close</a></div>'; 
            return({
                template: notification,
                restrict: "E"
            });

Is this the correct way?

Thanks in advance!

Upvotes: 1

Views: 745

Answers (2)

Mark Rajcok
Mark Rajcok

Reputation: 364697

If all of your views need this header, you should probably put the header in a separate view (with its own controller), and use ng-view to only change the main content area of your page.

If different views need to affect what is shown in the header (i.e., affect the model data of the header), then this model data should be put into a service, and the different views can then inject that service to affect the model.

I recently answered a SO question very similar to this, so I suggest looking at it too: https://stackoverflow.com/a/16065385/215945
That answer also references a question about a shopping basket with an item count that is in a header. The item count needed to be updated by multiple controllers, so we put it into a service.

Upvotes: 2

user2289659
user2289659

Reputation:

Yes this is correct. you can also follow this link : http://onehungrymind.com/angularjs-directives-basics/

Upvotes: 1

Related Questions