gpt4 book ai didi

javascript - AngularJS:如何将功能拆分为多个 Controller

转载 作者:行者123 更新时间:2023-11-29 22:05:46 25 4
gpt4 key购买 nike

我的应用程序中只有一个 Controller http://jsfiddle.net/HKF9h/ :

<div ng-controller="MyCtrl">
All Items:
<ul>
<li ng-repeat="item in items">{{item }} -
<a href="" ng-click="like(item)">like it</a>
</li>
</ul>
Items you liked:
<ul>
<li ng-repeat="item in likedItems">{{item }}
</li>
</ul>
</div>

<script type="text/javascript">
var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
$scope.items= ['foo', 'bar', 'z'];
$scope.likedItems = [];

$scope.like = function (item) {
if($scope.likedItems.indexOf(item) === -1) {
$scope.likedItems.push(item);
}
}
</script>
}

我想将所有“收藏”功能移到 sep Controller 中,以后可以重复使用。这就是我所做的,但中继器不再显示喜欢的项目。我做错了什么? http://jsfiddle.net/MR8wz/

<div ng-controller="MyCtrl">
All Items:
<ul>
<li ng-repeat="item in items">{{item }} -
<a href=""
ng-controller="FavoriteCtrl"
ng-click="like(item)">like it</a>
</li>
</ul>
Items you liked:
<ul ng-controller="FavoriteCtrl">
<li ng-repeat="item in likedItems">{{item }} //this one does not trigger
</li>
</ul>
</div>

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
$scope.items= ['foo', 'bar', 'z'];
}

function FavoriteCtrl($scope) {
$scope.likedItems = [];
$scope.like = function (item) {
console.log('you liked', item); //this one is displayed
if($scope.likedItems.indexOf(item) === -1) {
$scope.likedItems.push(item);
}
}
}

最佳答案

您不应该真的依赖 Controller 继承来共享数据。这是紧密耦合的坏情况。在 Angular 中,如果你想共享数据,建议你使用服务/工厂,因为:

  1. 它们很容易注入(inject)到您需要的任何地方
  2. 他们很容易模仿
  3. 它们很容易测试

FIDDLE

var myApp = angular.module('myApp',[]);

myApp.factory('Favorite', function(){
var likedItems = [];

function like(item) {
console.log('you liked', item); //this one is displayed
if(likedItems.indexOf(item) === -1) {
likedItems.push(item);
}
}

function getLikedItems(){
return likedItems;
};

return {
like: like,
getLikedItems: getLikedItems
};
});

function MyCtrl($scope, Favorite) {
$scope.favorite = Favorite;
$scope.items = ['foo', 'bar', 'z'];
}

function FavoriteCtrl($scope, Favorite) {
$scope.likedItems = Favorite.getLikedItems();
}
<div ng-controller="MyCtrl">
All Items:
<ul>
<li ng-repeat="item in items">{{item }} -
<a href=""
ng-controller="FavoriteCtrl"
ng-click="favorite.like(item)">like it</a>
</li>
</ul>
Items you liked:
<ul ng-controller="FavoriteCtrl">
<li ng-repeat="item in likedItems">{{item }}
</li>
</ul>
</div>

关于javascript - AngularJS:如何将功能拆分为多个 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21072956/

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