gpt4 book ai didi

javascript - 在 ng-view 之外更新 HTML 元素

转载 作者:可可西里 更新时间:2023-11-01 02:02:11 27 4
gpt4 key购买 nike

我在页面上有以下 HTML:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="myCart">
<head>
<title>AngularJS Shopping Cart</title>
<link href="css/jsonstore.css" rel="stylesheet" />
</head>
<body>
<div id="container">
<div id="header">
<h1>The JSON Store</h1>
<div class="cart-info">
My Cart (<span class="cart-items">{{item.basketCount}}</span> items)
</div>
</div>
<div id="main" ng-view>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular-resource.js"></script>
<script src="js/routing.js"></script>
<script src="js/dataresource.js"></script>
<script src="js/basketinfo.js"></script>
<script src="js/index.js"></script>
<script src="js/detail.js"></script>
</body>
</html>

div“main”被我的路由替换为 HTML 模板,但是我想用购物篮计数更新标题部分。

我已尝试按照 HTML 及以下所示对其进行模型绑定(bind):

function DetailController($scope, item, basketDetail) {
$scope.item = item;
$scope.item.basketCount = basketDetail.getCount();

//more code
}

我也试过只注入(inject)服务并从 HTML 调用它。两种方式都不做任何事情。

有人可以帮忙吗?

谢谢

最佳答案

您的 header div 实际上是一个 View ,就像您定义的用于 ng-view 的其他 View 一样。有一天,您可能希望在该标题 View 中显示的不仅仅是一个 basketCount 模型。但是,即使您将一个模型数据投影到该标题部分,这一事实也使该部分成为一个 View 。因此,我建议给它自己的 $scope 来投影该模型,因此它有自己的 Controller 。

剩下的就是将 basketCount 模型放在哪里?我们必须考虑到多个 View 可能允许用户做一些需要影响该模型的事情。 Angular 对“许多需要访问”的正常回答是依赖注入(inject)。因此,我会将 basketCount 模型放入服务中。需要访问它的 View / Controller 可以注入(inject)它。有一天,您的应用可能会有不需要访问这些模型的其他 View ,因此这些 View 不会注入(inject)服务。

可能,整个篮子都可以在此服务中建模:

app.factory('basketService', function() {
return {
items: [],
itemCount: 0,
...
}
});


function HeaderCtrl($scope, basketService) {
$scope.basket = basketService;
...
}

function DetailCtrl($scope, basketService) {
$scope.basket = basketService;
...
}

<div id="header" ng-controller="HeaderCtrl">
<h1>The JSON Store</h1>
<div class="cart-info">
My Cart (<span class="cart-items">{{basket.itemCount}}</span> items)
</div>

关于javascript - 在 ng-view 之外更新 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14608258/

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