Angularjs 如何从一个控制器获取一个变量,然后将同一个变量传递给视图

Angularjs 如何从一个控制器获取一个变量,然后将同一个变量传递给视图,angularjs,Angularjs,我有两个控制器ParentController和ChildController我在ParentController中有一个变量,我需要将该变量获取给ChildController,然后我需要将其传递给视图,还有一件事是我不应该在child controller和ParentController中使用$scope。有可能吗?如果没有,有没有办法在没有$scope的情况下使用它 app.controller('ParentController', function($scope) { $sc

我有两个控制器
ParentController
ChildController
我在ParentController中有一个变量,我需要将该变量获取给ChildController,然后我需要将其传递给视图,还有一件事是我不应该在child controller和ParentController中使用$scope。有可能吗?如果没有,有没有办法在没有$scope的情况下使用它

app.controller('ParentController', function($scope) {
    $scope.exampleVariable = "test";
});

app.controller('ChildController', function($scope, $controller) {
  var someScopeVariable = this;
  $controller('ParentController', {$scope: someScopeVariable });
  console.log(someScopeVariable.exampleVariable) 
  someScopeVariable.exampleVariable = "Updatetest";
});
现在在我的html视图中,我需要使用exampleVariable

像这样

<div ng-controller="ChildController as child">
     <h1>{{child.exampleVariable}}</h1>
</div>

{{child.exampleVariable}}

如何从parentcontroller到html视图获取值。

您可以在控制器中使用Broadcast和On-

app.controller('ParentController', function($scope) {
    var self = this;         
     $scope.$broadcast('exampleVariable', 'test');
});
而在儿童控制器中—

app.controller('ChildController', function($scope, $controller) {
var someScopeVariable = this;
$controller('ParentController', {$scope: someScopeVariable });
  console.log(someScopeVariable.exampleVariable) 

 $scope.$on('exampleVariable', function(event, data) {
 someScopeVariable.exampleVariable = data;
});

});

您始终可以使用服务在控制器之间共享数据

  • 创建服务
将其作为依赖项传递,就可以共享该值


您也可以将其作为依赖项传递给其他控制器,并且可以在那里执行getMyVar

有一些方法可以做到这一点

1. Through $rootScope.
2. By Creating Service.
3. Inheriting parent controller to children controller.
其他答案中已经提供了2和3。如果您想使用
$rootScope
实现它,请遵循此步骤

JS:

HTML:

<div ng-controller="ParentController">
  Parent Controller : {{exampleVariable}}
  <hr/>
</div>
<div ng-controller="ChildController">
   Children Controller : {{exampleVariable}}
</div>

我需要修改子控制器中的exampleVariable。如果我们像你上面提到的那样写信是不可能的
1. Through $rootScope.
2. By Creating Service.
3. Inheriting parent controller to children controller.
var app = angular.module('myApp', []);

app.controller('ParentController', function($scope, $rootScope) {
    $rootScope.exampleVariable = "test";
});

app.controller('ChildController', function($scope) {

});
<div ng-controller="ParentController">
  Parent Controller : {{exampleVariable}}
  <hr/>
</div>
<div ng-controller="ChildController">
   Children Controller : {{exampleVariable}}
</div>
$scope.exampleVariable = "overriding...";