[英]Calling a specific function Code Between Controllers using Services in Angular js
我有一個工廠,在其中保存要在各種控制器中重用的代碼。
當我在每個控制器上分別單擊ng並單擊它們時,其功能不起作用。
另外,有沒有更好的方法來處理這種情況?
視圖:
<body ng-app="MyApp">
<div ng-controller="MyCtrl" ng-click='hidepop()'>
<ul ng-repeat="user in users">
<li>{{user}}</li>
</ul>
<div class="nested" ng-click='showpop()' ng-controller="AnotherCtrl">
</div>
</div>
</body>
控制器:
var app = angular.module("MyApp", []);
app.factory("UserService", function ($window) {
var root={};
root.showpop = function () {
alert("f")
}
root.hidepop = function () {
alert("d")
}
return root;
});
app.controller("AnotherCtrl", function($scope,$location, UserService) {
$scope.alerter = UserService;
$scope.showpop(){
$scope.alerter.showpop();
}
$scope.alerter.hidepop();
});
app.controller("MyCtrl", function($scope, UserService) {
$scope.alerter = UserService;
$scope.alerter.showpop();
$scope.alerter.hidepop();
});
這是我的小提琴: 小提琴鏈接
我對代碼進行了一些調整,以顯示一種可以使用已開始構建的服務的方法-http : //jsfiddle.net/p8LNR/2/ :
HTML:
<body ng-app="MyApp">
<div ng-controller="MyCtrl">
<ul ng-repeat="user in users">
<li>{{user}}</li>
</ul>
<div class="nested" ng-click=showpop() ng-controller="AnotherCtrl">
</div>
</div>
</body>
Javascript:
var app = angular.module("MyApp", []);
app.factory("UserService", function() {
var users = ["Peter", "Daniel", "Nina"];
var root={
'showpop':function () {
alert("f")
},
'hidepop':function () {
alert("d")
},
'users': users
};
return root;
});
app.controller("AnotherCtrl", function($scope,$location, UserService) {
$scope.showpop = function(){
UserService.showpop();
}
$scope.hidepop = function(){
UserService.hidepop();
}
});
app.controller("MyCtrl", function($scope, UserService) {
$scope.users = UserService.users
});
以下是有關您的代碼的一些建議:
看來您正在開始構建可以修改DOM的東西(稱為popup),在這種情況下,您可能實際上想記住您可以使用html做很多事情,例如,創建“ pop-up”具有以下內容的窗口:
<div ng-style="showpopup">{{ selected_user.name}}</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.