How to reuse template html and js code?


#1

Hi.
I’m coming from php-development and this is my first app-attempt to develop a (even, hybrid) app. I’ve developed a basic tabs app wherein there are 4 tabs. Two of these tabs display a list of items, clicking on which takes me to the detail page of the app. Now, I’ve following concerns:

  1. While using PHP, I could easily reuse code by wrapping it within a function. So for example, if I want to use a part of html code over and over again, how do I do it, without having to write it again?
  2. At functional level as well, I want to reuse the code. For example, I’ve a ‘Like’ button below every item and there are different type of items, lets say, Reviews, products, and users. How do I implement a Like button HTML+JS code which I can use at the template as well as functional level?
    I could have posted the code as well but I hope you already have that from ionic’s tabs’ template code.

#2

In it’s simplest form you can use ng-include to re-use snippets of html.
https://docs.angularjs.org/api/ng/directive/ngInclude

If there is associated “js” you can create a controller and add it to your html via ng-controller.
https://docs.angularjs.org/api/ng/directive/ngController

Thats absolutely fine however the more angular way of doing it is to create a directive: https://docs.angularjs.org/guide/directive, if you are new to angular though I would stick to ng-include + ng-controller.


#3

Thanks man. Would implement this and will let you know if I’d face any issues. Thanks again :smile: