【问题标题】:Sync angular items (products)同步角度项目(产品)
【发布时间】:2014-12-05 11:30:17
【问题描述】:

假设我们有一些产品列表。我们通过 php 获取它们。例如:

$products = Product::all();

那么在我们看来:

<?php foreach ($products as $product): ?>
    <div class='product'>
        <div class="name"><?php echo $product->name ?></div>
        <div class="short-info"><?php echo $product->short ?></div>

        <div class="quantity">
            <button class="add-one">-</button>
            <input type="text" value="<?php echo $product->quantity ?>">
            <button class="remove-one">+</button>
        </div>
    </div>
<?php endforeach ?>

在 Angular 中我们会有这样的想法:

<div class='product' ng-repeat="product in products">
    <div class="name">{{ product.name }}</div>
    <div class="short-info">{{ product.short }}</div>

    <div class="quantity">
        <button class="add-one" ng-click="removeOne(product)">-</button>
        <input type="text" ng-model="{{ product.quantity }}">
        <button class="remove-one" ng-click="addOne(product)">+</button>
    </div>
</div>

但是我们怎样才能让这些东西协同工作呢? 我想立即用 php 填充 products(用于 seo puproses)并具有 angular 提供的功能。

**EXAMPLE:**
User navigate to http://.../catalog
User instantly see product list (because they were rendered with php)
User instantly can change product amount (here comes angular ng-model)

如何做到这一点?谢谢

【问题讨论】:

    标签: javascript php angularjs laravel angularjs-ng-repeat


    【解决方案1】:

    你可以使用

    <div class='product' ng-repeat="product in products" ng-init="products=<?php echo json_encode($products);?>">
       <div class="name">{{ product.name }}</div>
       <div class="short-info">{{ product.short }}</div>
    
        <div class="quantity">
            <button class="add-one" ng-click="removeOne(product)">-</button>
            <input type="text" ng-model="{{ product.quantity }}">
            <button class="remove-one" ng-click="addOne(product)">+</button>
        </div>
    </div>
    

    我不是php程序员,但你可以在这里得到想法。

    【讨论】:

    • 但是当您查看页面源 (take.ms/626VU) 时,将只有 angulars 模板(不是渲染产品)
    • 如果你用 ng-app 正确安装 Angular 模块并使用控制器,指令 ng-init 相当于在控制器中声明产品列表。因此页面上将列出具有正确绑定的产品。
    • 你可以自己测试一下,看看是不是。在“Cmd + opt + u”中你不会看到渲染的产品,因为它们是通过js渲染的
    • 在这种情况下,您可以在服务器上创建角度指令。示例:'
      {{ product.name }}
      ' 将是 '
      {{ products[].name }}
      '
    • 或者最简单的方法是初始化产品,例如之前的答案宽度 ng-init 和每个产品的产品的 js 索引相同,然后将绑定 {{ product.short }} 更改为 {{ products[index] .short }}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 2022-12-06
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多