ケース1:
使用子から親コントローラに値を渡す$emit
イベント。 Read docs for more info。
ケース2:
使用親から子コントローラに値を渡す$broadcast
イベント。 Read docs for more info。
$socpe.$broadcast("Some Value", $scope.someVar);
となど、それレシーブ他のコントローラで:
$scope.$on("Some Value", function(event, value){
console.log(value);
});
ケース3:
使用$rootscope
$broadcast
イベントへのコントローラは兄弟である場合。
$rootscope.$broadcast("Some Value", $scope.someVar);
、それレシーブ他のコントローラで:
$scope.$on("Some Value", function(event, value){
console.log(value);
});
例:私はあなたのサービスコールによって置き換えられます$timeout
を使用している例では
。変数は、タイムアウトコールで述べたように2秒後に更新されます。
angular
.module("app", [])
.controller("ParentCtrl", function($scope, $timeout){
$scope.parentVar = "This var belogs to ParentCtrl";
$scope.childSharedValue = "Waiting for ChildCtrl to pass value";
$scope.$on("Child Value", function(event, value){
$scope.childSharedValue = value;
});
$timeout(function(){
$scope.$broadcast("Parent Value", $scope.parentVar);
}, 2000);
})
.controller("ChildCtrl", function($scope, $timeout){
$scope.childVar = "This var belogs to ChildCtrl";
$scope.parentSharedValue = "Waiting for ParentCtrl to pass value";
$scope.$on("Parent Value", function(event, value){
$scope.parentSharedValue = value;
});
$timeout(function(){
$scope.$emit("Child Value", $scope.childVar);
}, 2000);
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ParentCtrl">
Parent Value: {{ parentVar}}<br />
Child Shared Value: {{ childSharedValue }}<br /><br />
<div ng-controller="ChildCtrl">
Child Value: {{ childVar}}<br />
Parent Shared Value: {{ parentSharedValue }}<br />
</div>
</div>
ので、何をしようとしたのですか?いくつかのコードを挿入します。 – DRPK