简体   繁体   中英

Partials in Angular but not ng-include/directives

There is a piece of code in my angular that is being repeated in two files. I made it a directive so it could be reusable. I'm sending it some data.

Let's assume this is the template:

<directive1 data="object"></directive1>

Here is the html of directive 1

<div class="a">{{data.x}}</div>
<div class="b">{{data.y}}</div>
<div class="c">{{ data.z}}</div>

Now let's say on some another place I want to have just the above two lines of the template. Since the css is completely different for that, I decided to create another directive rather than putting switching logic in the directive.

<directive2 data="similarObject"></directive2>

So now the issue is I want to have this in my directive 2 html:

<div class="a">{{data.x}}</div>
<div class="b">{{data.y}}</div>

But since this will be duplicated I'm confused how to go about doing it. I don't want to use ng-include since it loads the template asynchronously from client side. I just want to make my code modular so the HTML is not duplicated. I don't mind if the HTML is duplicated after building with my gulp system.

Isn't there any include that is included during the compile time? Since I'm using gulp as my build system, I'm hoping something like that exists so that I can do something like require('./something') like I do it in my Javascript.

It is possible to use one directive only. Add an extra attribute in the directive.

<directive1 data="object" type="page1"></directive1>

For calling from the second page where you needed extra styles:

<directive1 data="similarObject" type="page2"></directive1>

Suppose extra css lines of code are in the extra-css class. Hence we will set the class conditionally.

<div class="a" ng-class="{ 'extra-css' : type === 'page2' }">{{data.x}}</div>
<div class="b" ng-class="{ 'extra-css' : type === 'page2' }">{{data.y}}</div>
<div class="c" ng-if="type === 'page1'">{{ data.z}}</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM