gpt4 book ai didi

javascript - 为什么 ng-src 需要表达式?

转载 作者:行者123 更新时间:2023-11-29 14:45:36 25 4
gpt4 key购买 nike

first.html

<html>
<head>
</head>
<body ng-app="store">
<div ng-controller="StoreController as store">
<div ng-repeat="product in store.product | orderBy:'-price'">
<h1>{{product.name}}</h1>
<h1>{{product.price | currency}}</h1>
<h1>{{product.description}}</h1>
<img ng-src="{{product.image}}" />
<button ng-show="product.canPurchase"> Add to Cart</button>
<div>
</div>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>

应用程序.js

( function(){

var app=angular.module('store',[]);

app.controller('StoreController',storeFunction);

function storeFunction(){
this.product=gem;
}

var gem=[{
name:'Apple 5',
price :2.95,
description:'test description 5',
canPurchase :true,
image:'quick1.png'
}];

})();

我在学习AngularJS ,我遇到了 ng-src 和 ng-show 指令,我不明白为什么 ng-src 需要表达式来获取值,而 ng-show 不需要表达式。

ng-src="{{product.image}}"  // working 
ng-src="product.image" //not working

的情况下
ng-show="product.canPurchase"      //working   
ng-show="{{product.canPurchase}}" // working

plnkr

最佳答案

为什么要使用 ng-src

问题是 DOM 在 Angular 加载之前就加载了很多(因为 DOM 启动 Angular ),所以在 Angular 加载之前没有发生解析/插值,但是所有图像标签都准备好了,系统开始获取它们.此时,您的图片来源是 {{product.image}},它将首先尝试获取该图片,并返回错误。

ng-src 避免了这种默认行为,并在 Angular 准备就绪后将 src 添加到图像

为什么 {{}} curl

因为 Angular 以这种方式工作 当第一次加载 Angular 页面时,页面会在 Angular 框架开始寻找钩子(Hook)(例如 ng-app 和 ng-controller)的地方被引导。当它知道它需要为特定范围/代码块使用哪个模型时,它开始用它们的表达式值替换所有花括号

这可能会有帮助。

关于javascript - 为什么 ng-src 需要表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33360438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com