我正嘗試在AngularJs中的兩個不同控制器之間進行通信。我想實現的目標是在第一個控制器中使用變量的值,一旦通過用戶下拉選擇而不是我設置的默認值。但不幸的是第二個控制器使用第二個控制器中的變量的默認值。如何在第一個控制器中調用第二個控制器後才能在AngularJs中執行的控制器中的某個函數
我是Angular的新手,所以如果你認爲它沒有得到很好的表現,請原諒我。我來自數據科學背景。 這裏是我使用
<script>
var app = angular.module("BuildApp", []);
app.run(function ($rootScope) {
$rootScope.$on('scope.stored', function (event, data) {
console.log("scope.stored", data);
});
});
app.controller("BranchController", function ($scope, $http, Scopes) {
Scopes.store('BranchController', $scope);
$http.get('http://192.168.3.96:8082/engine-api/1.1/builds/getbranch').
success(function (data, status, headers, config) {
$scope.branchs = data;
}).
error(function (data, status, headers, config) {
console.log('Api call failed', status)
});
$scope.selectedBranch = 'Nothing Selected';
$scope.dropboxitemselectedbranch = function (item) {
$scope.selectedBranch = item;
}
});
app.controller("KitController", function ($scope, $http, Scopes) {
Scopes.store('KitController', $scope);
var url = 'http://192.168.3.96:8082/engine-api/1.1/builds/getkit?Branch=' + Scopes.get("BranchController").selectedBranch;
console.log(url)
$http.get(url).
success(function (data, status, headers, config) {
$scope.kits = data;
}).
error(function (data, status, headers, config) {
console.log('Api call failed', status)
});
$scope.selectedKit = "Nothing Selected";
$scope.dropboxitemselectedkit = function (item) {
$scope.selectedKit = item;
}
});
app.factory('Scopes', function ($rootScope) {
var mem = {};
return {
store: function (key, value) {
mem[key] = value;
},
get: function (key) {
return mem[key];
}
};
});
</script>
代碼和HTML的樣子以下
<body ng-app="BuildApp">
<h1>Branch</h1>
<div ng-controller="BranchController">
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> {{selectedBranch}}
<span class="caret"></span></button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1" >
<li ng-repeat="branch in branchs"><branch ng-click = "dropboxitemselectedbranch(branch.name)"> {{branch.name}} </branch></li>
</ul>
</div>
</div>
<h1>Kit</h1>
<div ng-controller="KitController">
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> {{selectedKit}}
<span class="caret"></span></button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu2" >
<li ng-repeat="kit in kits"><kit ng-click = "dropboxitemselectedkit(kit.name)">{{kit.name}}</kit></li>
</ul>
</div>
</div>
</body>