【问题标题】:How to bind view to multiple controllers in angular js如何在angular js中将视图绑定到多个控制器
【发布时间】:2015-03-23 16:39:00
【问题描述】:

我在网页 ParentContoller 和 ChildContoller 上有两个控制器。 如何将值从 ParentContoller.js 传递到 ChildContoller.js。 我可以将视图上的值从 parentContoller 绑定到子控制器视图。 但是我如何将它从一个 contoller.js 传递到另一个 contoller.js 以进行进一步操作。在角度 js 中将值从一个 contoller 传递到另一个 contoller 有哪些不同的方法。请帮助

 <div ng-controller="ParentContoller">
    <input type="text" ng-model="dataService.value1" />
</div>

 // Controller 2 view
<div ng-controller="ChildContoller">
    The value entered by user is {{dataService.value1}}
</div>

【问题讨论】:

标签: angularjs angularjs-scope angularjs-ng-repeat angular-ui


【解决方案1】:

最好和正确的方法是使用服务。

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

app.service('myService', [function () {

  this.data = "data";
}])

app.controller('ParentContoller', ['$scope', 'myService', function ($scope,myService) {
  $scope.myService = myService;
}]);

app.controller('ChildContoller', ['$scope', 'myService', function ($scope,myService) {
  $scope.myService = myService;
}]);

<div ng-controller="ParentContoller">
    <input type="text" ng-model="myService.data" />
</div>

 // Controller 2 view
<div ng-controller="ChildContoller">
    The value entered by user is {{myService.data}}
</div>

【讨论】:

    【解决方案2】:

    嵌套控制器:

    <div ng-controller="ParentContoller">
        <input type="text" ng-model="dataService.value1" />
    
      <div ng-controller="ChildContoller">
          The value entered by user is {{dataService.value1}}
      </div>
    
    </div>
    

    其他尝试:http://blog.codehate.com/sharing-data-between-controllers-in-angular-js/

    【讨论】:

      猜你喜欢
      • 2017-09-01
      • 2014-06-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2020-08-08
      • 2015-10-23
      • 1970-01-01
      • 2015-10-07
      相关资源
      最近更新 更多