无法更新子控制器范围可变

时间:2016-06-09 10:04:34

标签: javascript angularjs

我是角度js的新手,我无法弄清楚如何从父控制器更改子控制器范围变量。以下是代码段:



var mainApp = angular.module("mainApp", []);

var parentCtrl = function($rootScope, $scope, shareService, $log){ 
    shareService.setDetails($scope.pdetails);
}

var mainCtrl1 = function($rootScope, $scope, shareService, $log){
    $scope.msg = "Controller 1";
    $scope.details = shareService.details;//shareService.details;
}

var mainCtrl2 = function($rootScope, $scope, shareService){
    $scope.msg = "Controller 2";
    $scope.details = shareService.details;//shareService.details;
}

parentCtrl.$inject = ["$rootScope", "$scope", "shareService", "$log"];
mainCtrl1.$inject = ["$rootScope", "$scope", "shareService", "$log"];
mainCtrl2.$inject = ["$rootScope", "$scope", "shareService", "$log"];

 mainApp.controller("parentController", parentCtrl)
        .controller("mainController1", mainCtrl1)
        .controller("mainController2", mainCtrl2)
        .factory("shareService", function(){
            var shareData = {
                details : "sadfgs detaisdfadsfasdf..",
                setDetails: function(value){
                    this.details = value;
                }
            };
            return shareData;
        });

<html>
   <head>
      <title>Angular JS Views</title>
      <script src='lib/angular.js'></script>
      <script src='js/mainApp.js'></script>
      <script src='js/studentController.js'></script>
   </head>
   
   <body ng-app = 'mainApp' ng-controller='parentController' ng-strict-di>
     <div ng-controller='mainController1'>
       1. Msg : {{msg}}<br/>
          Share Details: {{details}}<br/><br/>
     </div>
     <div ng-controller='mainController2'>
       2. Msg : {{msg}}<br/>
          Share Details: {{details}}<br/><br/>
     </div>
     <input type='text' ng-model='pdetails'/>  
   </body>
</html>
&#13;
&#13;
&#13;

以下是Plunker链接:

https://plnkr.co/edit/hJypukqMmdHSEZMVnkDO?p=preview

2 个答案:

答案 0 :(得分:1)

为了从父控制器更改子控制器的值,您可以在$ scope上使用$ broadcast。 语法

$scope.$broadcast(event,data);

$ broadcast用于从当前范围触发到子范围的事件(带有数据)。 在子控制器中使用$ on来接收事件(带有数据)。

这里是代码段:

app.controller("parentCtrl",function($scope){
$scope.OnClick=function()
{
  $scope.$broadcast("senddownward",$scope.messege);
}
});
app.controller("childCtrl",function($scope){
$scope.$on("senddownward",function(event,data)
{
  $scope.messege=data;
});
});

在这个例子中,我在ng-click上播放事件,你可以使用其他一些自定义event.like $ watch on $ scope。

请参阅此示例 https://plnkr.co/edit/efZ9wYS2pukE0v4JsNCC?p=preview

P.S。您可以将事件名称从 senddownward 更改为您想要的任何内容

答案 1 :(得分:0)

由于范围继承,您可以直接访问父级的范围属性:

 <div ng-controller='mainController1'>
      Share Details: {{pdetails}}
 </div>

您的示例不起作用,因为控制器在呈现视图之前只执行一次,pdetails此时为空。

要监控对pdetails的更改,您可以在子控制器中使用$watch

$scope.$watch('pdetails', function(newVal) {
  $scope.details = newVal;
});