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

标签 javascript angularjs

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/

相关文章:

css - 使用机器人框架从 ng-repeat CSS 中选择特定链接

javascript - 一个函数在同一个类元素上触发点击

javascript - 使用 JavaScript 处理 Html &lt;input pattern> - 超出时失败

javascript - "JQuery Interface file"for Flow(来自 Facebook 的 JavaScript 静态类型检查器)?

javascript - 在 Angular 表达式中使用 jQuery 选择器的结果

javascript - 有条件地在 Angular Directive(指令)中加载模板

javascript - 我们如何从 Cypress 测试中调用在单独文件中编写的函数?

Javascript - 每次鼠标悬停时生成新颜色

javascript - 下拉选择框选项在 chrome 浏览器中不起作用

javascript - 如何防止点击时选择选项卡?