我是角度js的新手,以下代码在我的项目中使用我的问题是当我点击ng-click = addtocart(参数)时它没有响应子控制器。我可以调用子控制器?请帮帮我?
<div ng-app="" ng-controller="parentCtrl">
<ul>
<li ng-click="search('12345');">
<div >
<div>
<div><img src="ProfileImges/menu.jpg"/></div>
<div>Hello</div>
</div>
</div>
</li>
</ul>
<div ng-repeat="x in names">
<div ng-click="addToCart('SMN1');">
<div>
<h4> {{ x.Price }} per meal</h4>
<img ng-src="{{x.ImgSrc}}"/>
</div>
<div>
<img ng-src="{{x.UserImg}}"/>
<p><strong>{{x.Uname}}</strong><br>
<span>{{x.RewPer}} </span><br>
</p>
</div>
<h4>{{x.Mtitle}}</h4>
<span><strong>{{x.Cuisine}}</strong></span>
<p`enter code here`>{{x.Mdesc}}</p>
</div>
</div>
<div ng-controller="childCtrl">
<div>{{cartdetails.name }}</div>
<div>Price</div>
</div>
</div>
<script>
var sj=angular.module('MyApp', []);
sj.controller('parentCtrl', ['$scope','$http', function($scope, $http) {
$scope.search = function(param) {alert("enter123");
$http.get('AngularJs-Response.jsp?mid='+param).success(function(response) {
$scope.names = response;
});
};
$scope.addToCart=function(smid){
CallAddCart(smid);
};
}]);
function CallAddCart(smid) {
sj.controller('childCtrl', ['$scope','$http', function($scope, $http) {
$http.get('reponse.jsp?smid='+smid).success(function(response) {alert(response);
$scope.cartdetails = response;
});
}]);
};
</script>
答案 0 :(得分:5)
请参阅plnkr:http://plnkr.co/edit/IdsHc19xBUalZoIXPE2T?p=preview 简而言之,您可以通过$ broadcast和$ on API将$ scope作为事件总线从父控制器传送到子控制器:
angular.module("app", [])
.controller("ParentCtrl", function($scope) {
$scope.parentName = "parent";
$scope.onClick = function() {
$scope.parentName = "clicked";
$scope.$broadcast('onSearch', {myMsg: "hi children"});
}
})
.controller("ChildCtrl", function($scope) {
$scope.childName = "child";
$scope.$on('onSearch', function(event, obj) {
$scope.childName = obj.myMsg;
})
});
在父节点上调用onClick()后,父节点会在'onSearch'频道上向其所有子节目播放'name'。 ChildCtrl配置为侦听'onSearch'通道,一旦收到消息,就会执行回调函数。