如何真正prevent被投入与angularjs的DOM元素元素、prevent、angularjs、DOM

2023-09-13 04:38:30 作者:义婚孤女 time

假设你有以下code,显示部分产品图片:

Let's say you have the following code to display some products images:

<ul>
  <li ng-repeat="p in products">
    <img ng-src="/images/{{p.img}}"/>
  </li>
</ul>

现在让我们说一些产品很遗憾没有图像,您可以修复使用:

Now let's say some products unfortunately don't have images, you may fix that with:

<ul>
  <li ng-repeat="p in products">
    <img ng-hide="p.img==undefined" ng-src="/images/{{p.img}}"/>
  </li>
</ul>

现在去的萤火虫或Chrome开发人员工具网络选项卡,并检查图像下载 - 你会看到错误的,因为浏览器仍然试图下载不存在的图像。这是隐藏的,用户不会注意到,但当然是不好:不好的做法,不利于服务器性能,很坏很坏的坏...

Now go to the "network" tab of firebug or chrome developer tools and check for the images download -- you will see errors, because the browser still tried to download the non-existent image. It's hidden and the users won't notice, but of course it's bad: bad practice, bad for server performance, bad bad bad...

什么是正确的角的解决方案呢?

What is the correct "angular" solution for this?

推荐答案

要@阿朗的解决方案,另一种方法是使用的 NG-开关或的 NG-如果(V1.1.5中提供),其中添加/删除DOM元素,不同于NG-隐藏/ NG-显示:

An alternative to @Arun's solution is to use ng-switch or ng-if (available in v1.1.5), which add/remove DOM elements, unlike ng-hide/ng-show:

<ul>
  <li ng-repeat="p in products">
    <span ng-switch="p.img==undefined">
      <img ng-switch-when="false" ng-src="/images/{{p.img}}"/>
    </span>
  </li>
</ul>

采用NG-若见@罗布的回答的一个例子。

See @Rob's answer for an example using ng-if.