I've created document header with few buttons and the header is included from some of my views using ng-include
.
Each view has its own controller and each button has on-click event.
What is the best practice to handle such a case, in order to prevent code replication?
Thanks in advance.
Asked
Active
Viewed 452 times
0

Costa Mirkin
- 947
- 3
- 15
- 39
-
Could you make a controller for that template you are ng-including and use that controller to handle any click events specific to that template? – Logan Tegman Apr 30 '15 at 22:36
-
If you are reusing and making any DOM manipulation, i would suggest you write a directive, i would use ng-include in cases where the content is mostly static. follow this article http://stackoverflow.com/questions/24171893/angularjs-nginclude-vs-directive – Chandra Sekhar Walajapet Apr 30 '15 at 23:31
1 Answers
1
You could move that part of code to directive so that placing only directive element there would be enough, Code will be reuse as you want.
Html
<my-directive template-url="abc.html" click-function="refreshData()"></my-directive>
Directive
app.directive('myDirective', function(){
return {
restrict: 'AE',
templateUrl: function(ele, attr){
return attr.templateUrl
},
link: function(scope, element, attrs){
element.find('button').on('click', function(){
scope.$apply(function(){
scope.$eval(attrs.clickFunction())
});
})
}
}
})
Above directive you could pass your templateUrl
name in attribute which would do the work of ng-include
& for click event you need to pass click event reference on clickFunction
attribute. That will call on click of button.

Pankaj Parkar
- 134,766
- 23
- 234
- 299