Reputation: 891
I am using ng-include in my application. It's working, but I'm wondering if this is a good way of doing ng-include. The html inside the ng-include file is calling the function from its parent.
The example can be seen in this plunkr. The plunkr doesn't show the button, but the idea is the element from ng-include file is calling out its parent function. Is that bad practice? Is there an alternative for this? For example, the html in my ng-include contains this:
<button class="mybutton" ng-click="ctrl.parentFn"></button>
The reason I asked is because I have a directive where there is a default template with the buttons. If user want to specify custom template (like different positioning of the button, or more elements) they can specify the custom template but they are allowed to use the default functionality (ng-click) from its parent controller.
Any comments are really welcomed and appreciated.
Upvotes: 2
Views: 1597
Reputation: 136184
I can't debate on this point, but if you div has nested in several controller then you need to use $parent.$parent.$parent
, depending on controller hierarchy it could be increased in length.
So I'd suggest you to use controllerAs syntax which provide alias of controller & it can be accessible inside any div by using alias of any controller you can access its method.
Markup
<div ng-controller="MainCtrl as main">
{{ main.title }}
<div ng-controller="AnotherCtrl as another">
{{ another.title }}
<div ng-controller="YetAnotherCtrl as yet">
{{ yet.title }}
</div>
</div>
</div>
Refer this article for more detailed info.
Upvotes: 2