angular.js 如何在html里根据ng-class的判断条件显示不同的图片
时间: 2024-02-03 21:14:39 浏览: 34
可以使用ng-class指令来根据判断条件来动态设置class,然后在CSS中设置不同的背景图片。
例如,假设有两个图片"image1.jpg"和"image2.jpg",根据ng-class的判断条件,显示不同的图片。
HTML代码如下:
```
<div ng-class="{'image1': condition1, 'image2': condition2}"></div>
```
CSS代码如下:
```
.image1 {
background-image: url('image1.jpg');
}
.image2 {
background-image: url('image2.jpg');
}
```
其中,'condition1'和'condition2'是根据实际情况来判断的条件。当'condition1'为true时,显示'image1.jpg',当'condition2'为true时,显示'image2.jpg'。
相关问题
Angular html 怎么调用 js中的函数
在 Angular 中,可以通过以下几种方式来调用 JavaScript 函数:
1. 在 HTML 模板中使用事件绑定调用函数:
```
<button (click)="myFunction()">Click me</button>
```
2. 在组件类中定义一个公共函数,并在 HTML 模板中调用:
```
@Component({
selector: 'app-my-component',
template: '<button (click)="myFunction()">Click me</button>'
})
export class MyComponent {
myFunction() {
// your code here
}
}
```
3. 在 HTML 模板中使用 Angular 内置指令 `ng-click` 调用函数:
```
<button ng-click="myFunction()">Click me</button>
```
但是需要注意的是,如果你要在 Angular 中调用外部 JavaScript 函数,你需要在组件类中声明该函数,并在 `ngOnInit()` 生命周期钩子函数中引入外部 JavaScript 文件,例如:
```
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-my-component',
template: '<button (click)="myFunction()">Click me</button>'
})
export class MyComponent implements OnInit {
ngOnInit() {
const script = document.createElement('script');
script.src = 'path/to/your/external/js/file.js';
document.body.appendChild(script);
}
myFunction() {
// your code here
// call your external function here
}
}
```
这样就可以在 Angular 中调用外部 JavaScript 函数了。
<select class="btn topic" ng-model="domain" onchange="change(this)"> </select>
这段代码是一个 `<select>` 元素,其中使用了 Angular 的 `ng-model` 和 `onchange` 属性。下面是对代码的详细解释:
- `<select>` 元素:这是一个下拉列表元素,用于选择选项。
- `class="btn topic"`:这个 `class` 属性是为了应用 CSS 样式,`btn` 和 `topic` 是两个类名,可以根据需要自定义样式。
- `ng-model="domain"`:这个 `ng-model` 属性是 AngularJS 的指令,用于将选择的值绑定到 `domain` 变量上。当选择的值发生变化时,`domain` 变量的值也会相应更新。
- `onchange="change(this)"`:这个 `onchange` 属性是一个 JavaScript 事件处理函数,当下拉列表的选项发生改变时,会触发名为 `change` 的函数,并将当前 `<select>` 元素作为参数传递给该函数。
需要注意的是,这段代码使用了 AngularJS 的指令和事件处理函数,所以在使用之前需要确保已经引入了 AngularJS 库。另外,可以根据需要自定义类名和事件处理函数的名称,并在 JavaScript 代码中定义对应的函数来处理相应的逻辑。