通过javascript函数插入<br/>段落

时间:2015-12-27 23:27:05

标签: javascript angularjs

所以这里有重要的代码:

// app.js
$scope.buy = function(name, price) {
console.log(name, price);
$scope.cart[0].subtotal = $scope.cart[0].subtotal + price;
$scope.cart[0].items = $scope.cart[0].items + name + "\n"; // I tried using \n.
}


// index.html
<body ng-controller="StoreController">
<p>Search:</p><input type="text" ng-model="search" />
<input type="radio" name="order" ng-value="true" ng-model="reverse">$$$ - $</input>
<input type="radio" name="order" ng-value="false" ng-model="reverse">$ - $$$</input>
<hr>
<div ng-repeat="items in items | filter:search |orderBy:'price':reverse">
<img id="thumbnail" ng-src="{{ items.thumb }}" />
<h2>{{ items.name }}</h2>
<p>{{ items.price | currency}} </p>
<p>{{ items.desc }} </p>
<button ng-show="items.instock" ng-click="buy(items.name, items.price)">Buy {{items.name}}</button>
<p id="notStocked" ng-hide="items.instock">{{items.name}} is not in stock</p>
<hr>
</div>
<h1>Total Cart Price: {{ cart[0].subtotal }} </h1>
<p id="cartitems">Cart Items: {{ cart[0].items }}</p>
<button ng-show="subtotal > 0">Checkout</button>
</body>

我想使用buy()函数在cartitems段落中插入换行符,但我找不到答案。

1 个答案:

答案 0 :(得分:3)

将名称推送到数组。然后在ng-repeat代码上使用<span>

JS

$scope.cart[0].purchases = [];
$scope.buy = function(name, price) {
    $scope.cart[0].subtotal += price;
    $scope.cart[0].purchases.push(name);
};

HTML

<h1>Total Cart Price: {{ cart[0].subtotal }} </h1>
<p id="cartitems">Cart Items: 
    <span ng-repeat="name in cart[0].purchases track by $index">
        {{name}}<br>
    </span>
</p>