这是我的app.js
var app = angular.module("app",[]);
app.controller("myFirstController",['$scope',function($scope){
$scope.test = "myfirstName";
$scope.test1 = "myfirstName";
}])
app.controller("mySecondController",['$scope','$rootScope',function($scope,$rootScope){
$scope.test = "myLastName";
//Here how to call my test,test1 scope using $rootScope ??
}])
我可以使用$ rootScope吗?我不想使用任何emit
和broadcast
或this
答案 0 :(得分:0)
如果您在rootscope中存储任何值,如:
$rootScope.test =" value ";
您可以从rootScope中检索值,如
var value = $rootScope.test;
但是,用于数据维护和安全性并不好
因为如果刷新浏览器,则会清除所有范围值。
所以我建议你采取3种不同的方式
我不想使用任何发射和广播或
但这是唯一最适合pass value from one controller to another controller
的方法答案 1 :(得分:-1)
你可以这样做,但在某些情况下使用不同的名称来避免错误。如果你没有在第一个ctrl中将它声明为$ rootScope,那么它将在第二个ctrl中为undef
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body >
<div ng-controller="myFirstController">
</div>
<div ng-controller="mySecondController">
</div>
</body>
<script>
var app = angular.module('plunker', []);
app.controller("myFirstController",['$scope','$rootScope',function($scope,$rootScope){
$rootScope.test = "myfirstName";
}])
app.controller("mySecondController",['$scope','$rootScope',function($scope,$rootScope){
$scope.test = "myLastName";
console.log($rootScope.test);
//Here how to call my myFirstName scope using $rootScope ??
}])
</script>
</html>