无法更新子控制器范围可变 [英] Unable to update Child controllers scope valriable
问题描述
我是angular js的新手,无法弄清楚如何从父控制器更改子控制器作用域变量.这是该代码段:
Im new to angular js and im not able to figure out how to change the child controller scope variable from parent controller. Here is the code snippet for that:
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>
以下是"Plunker"链接:
Here is the Plunker link:
https://plnkr.co/edit/hJypukqMmdHSEZMVnkDO?p=preview
推荐答案
要从父控制器更改子控制器的值,可以在$ scope上使用$ broadcast.语法
In order to change value of child controller from parent controller you can use $broadcast on $scope. syntax
$scope.$broadcast(event,data);
$ broadcast用于触发从当前作用域到子作用域的事件(带有数据).在子控制器中,使用$ on接收事件(带有数据).
$broadcast is used to trigger an event(with data) to the child scope from current scope. In child controller use $on to receive the event(with data).
此处是代码段:
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广播事件,您可以使用其他自定义事件,例如$ scope上的$ watch.
In this example I am broadcasting the event on ng-click,you can use some other custom event.like $watch on $scope.
请参阅此示例 https://plnkr.co/edit/efZ9wYS2pukE0v4JsNCC?p=preview
P.S.您可以将事件的名称从 senddownward 更改为所需的名称
P.S. you can change the name of event from senddownward to whatever you want
这篇关于无法更新子控制器范围可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!