如何将视图绑定到角度js中的多个控制器

时间:2015-03-23 07:44:12

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

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

 <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>

2 个答案:

答案 0 :(得分:0)

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

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>

答案 1 :(得分:0)

嵌套控制器:

<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/