我的应用程序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控制器中,以后可以重复使用。这就是我所做的,但转发器不再显示likesItems了。我做错了什么? 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);
}
}
}
答案 0 :(得分:2)
您不应该依赖控制器继承来共享数据。这是一个紧密耦合的坏情况。 在Angular中,如果您想共享数据,建议您使用服务/工厂,因为:
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>
答案 1 :(得分:0)
您使用ng-controller
指令两次
<a href="" ng-controller="FavoriteCtrl" ng-click="like(item)">like it</a>
和
<ul ng-controller="FavoriteCtrl">
它会创建两个不同的scope
,这就是它不起作用的原因。所以,如果你移动
$scope.likedItems = [];
中的 MyCtrl
然后就可以了。更新
fiddle