Angular1 兄弟控制器如何访问彼此的数据

Angular1 sibling Controllers how can access each others data

我想在SecondCtrl中获取FirstCtrl数据,但是在SecondCtrl中没有反应,请帮我解决这个问题

我试过在 $rootscope 上使用 $broadcast 和 $emit。但是

上 $on 没有数据
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);

myApp.controller('FirstCtrl', function( $scope,  $rootScope) {
    $scope.firstName = 'Ganpat';
    //$rootScope.$emit('firstName', $scope.firstName);
    $rootScope.$broadcast('firstName:broadcast', $scope.firstName);
});

myApp.controller('SecondCtrl', function( $scope,  $rootScope){
  $rootScope.$on('firstName:broadcast', function(event,data){
    $scope.firstName = data;
    console.log(data);
  });
});
</script>
<body>

  <div ng-app="myApp">
    <div ng-controller="FirstCtrl">
      <input type="text" ng-model="firstName">
      <br>Input is : <strong>{{firstName}}</strong>
    </div>
    <hr>
    <div ng-controller="SecondCtrl">
      Input should also be here: {{firstName}}
    </div>
  </div>
</body>
</html>

代码现在可以正确编译和 运行s。您可以将其剪切并传递到 fiddler 和 运行.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
    var myApp = angular.module('myApp', []);

    myApp.factory('UserService', function () {
        var self = this;
        var firstName = '';
        self.SetFirstName = function (name) { firstName = name; }
        self.GetFirstName = function () { return firstName; }
        return self;
    });

    myApp.controller('FirstCtrl', ['$scope', 'UserService', function ($scope, UserService) {

        UserService.SetFirstName("coolMan");
    }]);

    myApp.controller('SecondCtrl', ['$scope', 'UserService', function ($scope, UserService) {
        $scope.firstNameTest = '';
        $scope.service = UserService;
        $scope.$watch('service.GetFirstName()', function (newVal) {
            console.log("New Data", newVal)
            $scope.firstNameTest = newVal;
        });
    }]);

</script>
<body>

    <div ng-app="myApp">
        <div ng-controller="FirstCtrl">
            <input type="text" ng-model="firstName">
            <br>
            Input is : <strong>{{firstName}}</strong>
        </div>
        <hr>
        <div ng-controller="SecondCtrl">
            Input should also be here: {{firstNameTest}}
        </div>
    </div>
</body>
</html>

编辑

正在处理 OPS 评论。

I know this method will work and it will give a correct result, but i have studied the $rootscope and event $emiter and $broadcast will do this trick, so if you know about that then please tell me, thank you for your answer.

你想做的是个坏主意。您的方法强制控制器之间的耦合更紧密。通过在 rootscope 上工作,您将强制所有控制器依赖于 rootscope 中的某个项目。这很糟糕,因为控制器不是独立的模块。

通过传递服务,您可以解耦控制器。这意味着它们可以用作视图控制器、指令控制器,几乎任何需要隔离模块的东西。

现在还可以使用服务来缓存结果,对其执行集中的业务逻辑,并封装获取数据的方式。这在 rootscope 上不容易完成。

总而言之,我不会向您展示做您想做的事情的糟糕方法。这不好,会让其他人看到这个 post 使用不好的做法。