javascript - 一个 Controller 如何从另一个 Controller 获取值(value)?

标签 javascript angularjs

Angular 应用。使用 ui-select。

<div class="col-md-12" ng-controller="FlatController as flat">
   <form ng-submit="flat.createFlat()">
      <ui-select ng-model="flat.flatData.typelocal" theme="bootstrap">
          <ui-select-match placeholder="Type" id="localtype">
              {{ $select.selected.type }}
          </ui-select-match>
          <ui-select-choices repeat="uitypelocal.type as uitypelocal in flat.typelocal1 track by $index | filter: $select.search">
             <div ng-bind-html="uitypelocal.type | highlight: $select.search"></div>
          </ui-select-choices>
      </ui-select>
       <button class="btn btn-danger">Send</button>
  </form>
</div>

在表单中我有一些输入和选择。现在,我想从另一个 Controller 中选择数据。我该怎么做?

我有一个服务:

angular.module('flatService', [])
    .factory('Flat', function($http){
        var flatFactory = {};

        flatFactory.allFlats = function(){
            return $http.get('/api/flats');
        };

        flatFactory.create = function(flatData){
            return $http.post('/api/addflat', flatData);
        };

        return flatFactory;

    })
});

最佳答案

如果你想将一个 Controller 调用到另一个 Controller ,有五种方法可用

  1. $rootScope.$emit() 和 $rootScope.$broadcast()
  2. 如果第二个 Controller 是子 Controller ,您可以使用父子通信。
  3. 使用服务
  4. 有点技巧 - 在 angular.element() 的帮助下
  5. 注入(inject)“$controller”

1. $rootScope.$emit() and $rootScope.$broadcast()

Controller 及其作用域可以被破坏, 但是 $rootScope 保留在整个应用程序中,这就是我们采用 $rootScope 的原因,因为 $rootScope 是所有范围的父级。

如果你正在执行从 parent 到 child 的交流,甚至 child 想和它的 sibling 交流,你可以使用 $broadcast

如果你正在执行从 child 到 parent 的沟通,没有 sibling 参与,那么你可以使用 $rootScope.$emit

HTML

<body ng-app="myApp">
    <div ng-controller="ParentCtrl" class="ng-scope">
      // ParentCtrl
      <div ng-controller="Sibling1" class="ng-scope">
        // Sibling first controller
      </div>
      <div ng-controller="Sibling2" class="ng-scope">
        // Sibling Second controller
        <div ng-controller="Child" class="ng-scope">
          // Child controller
        </div>
      </div>
    </div>
</body>

Angularjs 代码

 var app =  angular.module('myApp',[]);//We will use it throughout the example 
    app.controller('Child', function($rootScope) {
      $rootScope.$emit('childEmit', 'Child calling parent');
      $rootScope.$broadcast('siblingAndParent');
    });

app.controller('Sibling1', function($rootScope) {
  $rootScope.$on('childEmit', function(event, data) {
    console.log(data + ' Inside Sibling one');
  });
  $rootScope.$on('siblingAndParent', function(event, data) {
    console.log('broadcast from child in parent');
  });
});

app.controller('Sibling2', function($rootScope) {
  $rootScope.$on('childEmit', function(event, data) {
    console.log(data + ' Inside Sibling two');
  });
  $rootScope.$on('siblingAndParent', function(event, data) {
    console.log('broadcast from child in parent');
  });
});

app.controller('ParentCtrl', function($rootScope) {
  $rootScope.$on('childEmit', function(event, data) {
    console.log(data + ' Inside parent controller');
  });
  $rootScope.$on('siblingAndParent', function(event, data) {
    console.log('broadcast from child in parent');
  });
});

在上面的代码控制台中,$emit 'childEmit' 不会在子 sibling 内部调用,它只会在父级内部调用,其中 $broadcast 在 sibling 和父级内部也会被调用。这是性能发挥作用的地方。 $emit 是更可取的,如果你正在使用 child 与 parent 的沟通,因为它会跳过一些脏检查。

2. If Second controller is child, you can use Child Parent communication

这是最好的方法之一,如果您想在 child 想要与直系 parent 交流的地方进行 child parent 交流,那么它不需要任何类型的$broadcast或$emit 但如果你想从 parent 到 child 进行交流,那么你必须使用服务或 $broadcast

例如 HTML:-

<div ng-controller="ParentCtrl">
 <div ng-controller="ChildCtrl">
 </div>
</div>

Angular

 app.controller('ParentCtrl', function($scope) {
   $scope.value='Its parent';
      });
  app.controller('ChildCtrl', function($scope) {
   console.log($scope.value);
  });

每当您使用子到父通信时,Angularjs 都会在子内部搜索一个变量,如果它不存在,那么它会选择查看父 Controller 中的值。

3.Use Services

AngularJS 使用服务架构支持“关注点分离” 的概念。服务是 javascript 函数,只负责执行特定任务。这使它们成为独立实体可维护和可测试。服务用于使用 Angularjs 的依赖注入(inject)机制进行注入(inject).

Angularjs 代码:

app.service('communicate',function(){
  this.communicateValue='Hello';
});

app.controller('ParentCtrl',function(communicate){//Dependency Injection
  console.log(communicate.communicateValue+" Parent World");
});

app.controller('ChildCtrl',function(communicate){//Dependency Injection
  console.log(communicate.communicateValue+" Child World");
});

它将给出输出 Hello Child World 和 Hello Parent World 。根据服务的 Angular 文档,Singletons – 每个依赖于服务的组件都获得对服务工厂生成的单个实例的引用

4.Kind of hack - with the help of angular.element()

此方法通过其 Id/unique class.angular.element() 方法从元素获取 scope() 方法返回元素,而 scope() 使用一个 Controller 内部的 $scope 变量给出另一个变量的 $scope 变量不是一个好的做法。

HTML:-

<div id='parent' ng-controller='ParentCtrl'>{{varParent}}
 <span ng-click='getValueFromChild()'>Click to get ValueFormChild</span>
 <div id='child' ng-controller='childCtrl'>{{varChild}}
   <span ng-click='getValueFromParent()'>Click to get ValueFormParent </span>
 </div>
</div>

Angularjs:-

app.controller('ParentCtrl',function($scope){
 $scope.varParent="Hello Parent";
  $scope.getValueFromChild=function(){
  var childScope=angular.element('#child').scope();
  console.log(childScope.varChild);
  }
});

app.controller('CarentCtrl',function($scope){
 $scope.varChild="Hello Child";
  $scope.getValueFromParent=function(){
  var parentScope=angular.element('#parent').scope();
  console.log(parentScope.varParent);
  }
}); 

在上面的代码中, Controller 在 Html 上显示了它们自己的值,当您单击文本时,您将在控制台中相应地获得值。如果您单击父 Controller span,浏览器将控制子 Controller 的值,反之亦然。

5.inject '$controller'

您可以在父 Controller (MessageCtrl)中注入(inject)“$controller”服务,然后使用以下方法实例化/注入(inject)子 Controller (DateCtrl):
$scope.childController = $controller('childController', { $scope: $scope.$new() });

现在您可以通过调用子 Controller 的方法来访问数据,因为它是一项服务。
如果有任何问题,请告诉我。

关于javascript - 一个 Controller 如何从另一个 Controller 获取值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31637885/

相关文章:

javascript - 单值或常量值时在 x 轴上绘制的样条图 - highchart

javascript - Ng-if - 尝试获取我的 Firebase 的数据

javascript - 根据 Angular 中的单独变量设置下拉菜单默认值

javascript - 使用 length 函数返回 undefined

javascript - 未捕获的 TypeError : jQuery. event.addProp 不是函数

javascript - 在 iOS 和 Android 上打开键盘时,如何将元素保留在页面底部?

javascript - 使用扩展运算符组合未知数量的对象

javascript - 如何使用大量粒子获得更好的性能? Canvas

javascript - 使用 JavaScript 从另一个页面获取内容

javascript - 白色圆圈显示搜索工具栏