我可以使用一个Angular控制器来改变另一个吗?

时间:2016-05-23 19:07:38

标签: javascript angularjs

我带着一群随机动物,展示了两只动物,然后当我点击一只动物的按钮时,我希望那一只动物留下来,另一只动物换掉新动物。现在,我可以改变我想要留在的动物,但无法弄清楚如何跨越"并更改其他控制器的视图。

我尝试过设置ng-click =" 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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

如果您只想在控制器之间进行简单的事件交换,则可以使用 $ scope。$ emit和$ scope。$ on

@Bean
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public SampleTestClass sampleTest(SampleTest dependency) {
    return new SampleTestClass(dependency);
}

More on $scope events in official docs

答案 1 :(得分:0)

如您所述,您可以使用服务与控制器之间进行通信。

如果要自动更新其他控制器更新,您需要观看它。

http://plnkr.co/edit/iLnlZDyR1cZUQIiJJJEp

&#13;
&#13;
(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
}];
})();
&#13;
<!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>
&#13;
&#13;
&#13;