【问题标题】:AngularJS passing objects from main controllers to other controllersAngularJS 将对象从主控制器传递到其他控制器
【发布时间】:2016-11-25 19:42:29
【问题描述】:

我是 Angularjs 和 Ionic 的新手。我目前正在构建我的第一个应用程序,我想知道,有什么方法可以在主控制器中注入表达式并在所有其他控制器中使用它们。

所以不要在每个控制器中输入 $scope、$http、$Ionicpopup。我想把它放在我的主控制器中并在所有其他控制器中使用它们。

var app=angular.module('app.controllers', []);

你能告诉我这叫什么吗?

【问题讨论】:

  • 不,不幸的是,您必须将它们注入需要这些依赖项的每个控制器中。这就是角度的工作原理。至于你的第二个问题,那将是一个角度模块。
  • @hsiung,我明白了,你能告诉我是否有一种方法可以让我自己表达并在不同的控制器中使用它?无需在每个控制器中初始化它
  • 你可以inherit controllers 大多数建议使用服务并在作用域上发出事件以在控制器之间进行通信

标签: javascript angularjs


【解决方案1】:

要创建自己的表达式并在代码的其他部分使用它,请尝试以下操作:

var myApp=angular.module('myApp', []);
myApp.value('clientId', 'a12345654321x'); // this sets a value

那么,如果你在任何地方包含 clientId 作为依赖项,那么无论它被注入到哪里,它都将等于 a12345654321x

要在其他地方使用您的值,只需将其作为依赖项包含进来

myApp.controller('mycontroller', ['clientId', function(clientId) {
    console.log(clientId);
}]);

对于更复杂的行为,您可以使用其他类型的 AngularJS 提供程序,例如工厂。这是供参考的文档:https://docs.angularjs.org/guide/providers

【讨论】:

    【解决方案2】:

    我们通常使用服务在控制器之间进行通信。

    在下面的示例中,我们创建 animalService,并将其注入到两个控制器中。然后我们使用 $watch 来监控变化。

    http://plnkr.co/edit/hfKuxJO2XZdB6MsK7Ief

    (function () {
    
        angular.module("root", [])
          .controller("leftAnimal", ["$scope", "animalService",
            function ($scope, animalService) {
    
                $scope.findNewAnimal = function () {
                    var randNum = Math.floor(Math.random() * animalPool.length);
                    $scope.animal = animalPool[randNum];
                    console.log("Left Click Index: " + randNum);
                    animalService.setAnimal(randNum);
                };
    
                $scope.$watch(function () {
                    return animalService.getAnimal();
                }, function (value) {
                    $scope.animal = animalPool[value];
                });
            }
          ])
          .controller("rightAnimal", ["$scope", "animalService",
            function ($scope, animalService) {
    
                $scope.findNewAnimal = function () {
                    var randNum = Math.floor(Math.random() * animalPool.length);
                    $scope.animal = animalPool[randNum];
                    console.log("Right Click Index: " + randNum);
                    animalService.setAnimal(randNum);
                };
    
                $scope.$watch(function () {
                    return animalService.getAnimal();
                }, function (value) {
                    $scope.animal = animalPool[value];
                });
            }
          ])
          .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 data-require="bootstrap-css@3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
        <script>document.write('<base href="' + document.location + '" />');</script>
        <link rel="stylesheet" href="style.css" />
        <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></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>

    【讨论】:

    • 谢谢,这就是我想要的。非常感谢您粘贴所有代码,这有助于我更好地理解!
    【解决方案3】:

    在 AngularJS 中,您必须将依赖项注入每个控制器。这样一来,每个控制器只具有它需要的依赖项,而不是任何无关的依赖项。

    线

    var app=angular.module('app.controllers', []);
    

    就是你告诉 AngularJS 你想创建一个新模块的方式。然后将东西添加到模块中,您只需调用类似

    app.controller('controllerName', function() {/* your stuff here */});
    app.filter('filterName', function() {/* your stuff here */});
    

    【讨论】:

    • 感谢您的回答。那么我还有一个问题,有没有一种方法可以让我自己表达并在不同的控制器中使用它?无需在每个控制器中初始化它
    • 是的,看看我刚刚发布的新答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多