为什么 http://plnkr.co/edit/sjmRT8XOCYPW3ntEnN3N?p=preview工作和http://plnkr.co/edit/Tkizktj0kx3OQmAkSH6U?p=preview不是。
唯一的区别是 Cart.js 中的 cartContent.push(product);
VS cartContent = [{name: "Keyboard"}];
我能看到的唯一区别是 Angular 对象(创建后有一个)$$hashKey
键...
我想完全重写对象 cartContent
并使其仍然可供 cartBoxCtrl
和 productListCtrl
最佳答案
这是因为在第二种情况下,您将覆盖被设置为对 $scope.cart
的引用的 cartContent,因此对 cart
所做的任何更改都不会反射(reflect)出来当您覆盖内容时,在作用域中,因为 $scope.cart 仍然指向旧的引用。因此,在您的 Controller 中将 $scope.cart
设置为 Cart
服务并在 ng-repeat 中访问 cartContent,以便 scope.cart
现在具有对 Cart 对象本身的引用以及对其属性所做的任何更改也将反射(reflect)在范围的属性中。
controller('cartBoxCtrl', function ($scope, Cart){
$scope.cart = Cart; //<-- here
});
和
<li ng-repeat="product in cart.cartContent track by $index">
另请注意 track by 的用法(这里我使用了 $index,相反,您可以在对象 ex:-product.id 上使用唯一属性),以便通过该属性而不是 Angular 创建的唯一键来跟踪列表$$haskkey
<强> Plnkr
或者,如果您想清理 cartContent 并仍将 cartContent 作为 $scope.cart
中的引用,那么您可以执行以下操作:-
this.addProduct = function (product) {
//Cleanup the current array and insert new item
this.cartContent.splice(0, this.cartContent.length, product);
};
<强> Plnkr
关于javascript - 使用 AngularJS 服务共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25818507/