我正在隨機動物池,顯示兩個,然後當我點擊一個動物的按鈕,我想要一個留下來,另外換一個新的被換出。現在,我可以改變我想留在視野中的動物,但無法弄清楚如何「跨越」並改變其他控制器的視圖。我可以使用一個角度控制器來改變另一個嗎?
我試過在右側設置NG點擊=「left.findNewAnimal()」,但我得到的點擊沒有反應。 我也看了使用service or factory,但我不能共享控制器之間的數據,我想改變一個數據,從其他。這如何實現?
的JavaScript:
angular.module("root", [])
.controller("leftAnimal", ["$scope",
function($scope) {
var self = this;
var animal
$scope.findNewAnimal = function() {
var randNum = Math.floor(Math.random() * animalPool.length);
animal = animalPool[randNum];
animalPool.splice(randNum, 1)
changeAnimal();
};
$scope.findNewAnimal();
function changeAnimal() {
$scope.name = animal.name;
$scope.img = animal.img;
}
}
])
.controller("rightAnimal", ["$scope",
function($scope) {
var self = this;
var animal
$scope.findNewAnimal = function() {
var randNum = Math.floor(Math.random() * animalPool.length);
animal = animalPool[randNum];
animalPool.splice(randNum, 1)
changeAnimal();
};
$scope.findNewAnimal();
function changeAnimal() {
$scope.name = animal.name;
$scope.img = animal.img;
}
}
])
.factory();
var Animal = function(data) {
this.name = data.name
this.img = data.img;
this.baby = data.baby;
};
var animals = [{
name: "Baby Quetzal",
img: "http://i.imgur.com/CtnEDpM.jpg",
baby: true
}, {
name: "Baby Otter",
img: "http://i.imgur.com/1IShHRT.jpg",
baby: true
}, {
name: "Baby Octopus",
img: "http://i.imgur.com/kzarlKW.jpg",
baby: true
}];
var animalPool = [];
var init = function() {
animals.forEach(function(animalData) {
animalPool.push(new Animal(animalData));
});
}
init();
<!doctype html>
<html ng-app="root">
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>
<div class="row">
<div class="text-center">
<h2>Pick an Animal</h2>
</div>
<div ng-controller="leftAnimal" class="col-md-6">
<div class="animalImage">
<img class="img-center" ng-src="{{img}}">
</div>
<div class="animalName">{{name}}</div>
<div class="animalDescription">{{description}}</div>
<button type="button" ng-click="findNewAnimal()" class="btn btn-info img-center">{{name}}</button>
</div>
<div ng-controller="rightAnimal" class="col-md-6">
<div class="animalImage">
<img class="img-center" ng-src="{{img}}">
</div>
<div class="animalName">{{name}}</div>
<div class="animalDescription">{{description}}</div>
<button type="button" ng-click="leftAnimal.findNewAnimal()" class="btn btn-info img-center">{{name}}</button>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="js/ang.js"></script>
</html>
感謝您抽出時間來幫我,但是這改變兩個圖像,我想只改變一個 –
我更新的代碼。點擊按鈕時,其他控制器的圖像將被更改。 – Win