我可以使用一个Angular控制器更改另一个吗? [英] Can I use one Angular controller to change another?

查看:17
本文介绍了我可以使用一个Angular控制器更改另一个吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要带一个随机的动物池,显示两个动物,然后单击一个动物的按钮时,我希望其中一个留着,而另一只换成新的.现在,我可以更改要停留在视野中的动物,但无法弄清楚如何跨越"并更改另一个控制器的视野.

I'm taking a pool of random animals, displaying two, then when I click the button of one animal, I want that one to stay and the other to be swapped out for a new one. Right now, I can change the animal that I want to stay in view, but can't figure out how to "reach across" and change the other controller's view.

我尝试在右侧设置ng-click ="left.findNewAnimal()",但单击时无响应.我还研究了使用服务或工厂,但是我我不在控制器之间共享数据,我想更改一个控制器的数据.如何做到这一点?

I've tried setting ng-click="left.findNewAnimal()" on the right side but I get no response on click. I've also looked at using a service or factory, but I'm not sharing data between controllers, I want to change the data of one, from the other. How can this be accomplished?

JavaScript:

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>

推荐答案

如前所述,您可以使用Service在控制器之间进行通信.

As you stated, you can use Service to communicate to between controllers.

如果要自动更新其他控制器更新,请观看它.

If you want to update other controller update automatically, you want to watch it.

http://plnkr.co/edit/iLnlZDyR1cZUQIiJJJEp

(function () {

angular.module("root", [])
  .controller("leftAnimal", ["$scope", "animalService",
    function ($scope, animalService) {
        var source = false;
        $scope.findNewAnimal = function () {
            var randNum = Math.floor(Math.random() * animalPool.length);
            console.log("Left Click Index: " + randNum);
            animalService.setAnimal(randNum);
            source = true;
        };

        $scope.$watch(function () {
            return animalService.getAnimal();
        }, function (value) {
            if(!source) {
              $scope.animal = animalPool[value];
            }
            source = false;
        });
    }
  ])
  .controller("rightAnimal", ["$scope", "animalService",
    function ($scope, animalService) {
       var source = false;
        $scope.findNewAnimal = function () {
            var randNum = Math.floor(Math.random() * animalPool.length);
            console.log("Right Click Index: " + randNum);
            animalService.setAnimal(randNum);
            source = true;
        };

        $scope.$watch(function () {
            return animalService.getAnimal();
        }, function (value) {
            if(!source) {
              $scope.animal = animalPool[value];
            }
            source = false;
        });
    }
  ])
  .factory("animalService", [function () {
      var index = 0;
      function getAnimal() {
          return index;
      }
      function setAnimal(newIndex) {
          index = newIndex;
      }
      return {
          getAnimal: getAnimal,
          setAnimal: setAnimal,
      }
  }]);

var animalPool = [{
    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
}];
})();

<!DOCTYPE html>
<html ng-app="root">
<head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
    <script src="app.js"></script>
</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="{{animal.img}}"/>
            </div>
            <div class="animalName">{{animal.name}}</div>
            <div class="animalDescription">{{animal.description}}</div>
            <button type="button" ng-click="findNewAnimal()"
                    class="btn btn-info img-center">
                Change
            </button>
        </div>
        <div ng-controller="rightAnimal" class="col-md-6">
            <div class="animalImage">
                <img class="img-center" ng-src="{{animal.img}}" />
            </div>
            <div class="animalName">{{animal.name}}</div>
            <div class="animalDescription">{{animal.description}}</div>
            <button type="button" ng-click="findNewAnimal()"
                    class="btn btn-info img-center">
                Change
            </button>
        </div>
    </div>
</body>
</html>

这篇关于我可以使用一个Angular控制器更改另一个吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆