我是棱角分明的新手。我试图保存并分享两个不同控制器的范围。
以下是我的剧本和观点。
的script.js:
0.8.5.6
的index.html:
var app = angular.module('app', ['ngRoute']);
app.run(function ($rootScope) {
$rootScope.$on('scope.stored', function (event, data) {
console.log("scope.stored", data);
});
});
app.controller('FirstController', function($scope) {
$scope.counter = 0;
$scope.add = function(amount) { $scope.counter += amount; };
$scope.subtract = function(amount) { $scope.counter -= amount; };
});
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/v1', {
templateUrl: 'views/v1.ejs',
controller: 'controller1'
}).
when('/v2', {
templateUrl: 'views/v2.ejs',
controller: 'controller2'
})
}]);
app.controller('controller1', function($scope,Scopes) {
Scopes.store('controller1',$scope);
$scope.data = "controller1";
$scope.buttonClick = function () {
console.log( Scopes.get('controller2').data);
};
});
app.controller('controller2', function($scope,Scopes) {
Scopes.store('controller2',$scope);
$scope.data = "controller2";
$scope.buttonClick = function () {
console.log( Scopes.get('controller1').data);
};
});
app.factory('Scopes', function ($rootScope) {
var mem = {};
return {
store: function (key, value) {
$rootScope.$emit('scope.stored', key);
mem[key] = value;
},
get: function (key) {
return mem[key];
}
};
});
v1.ejs:
<!doctype html>
<html ng-app="app">
<head>
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script src="js/script.js"> </script>
</head>
<body>
<a href='#v1'>View1</a>
<a href='#v2'>View2</a>
<div ng-view>
</div>
</body>
</html>
v2.ejs:
<div ng-controller="controller1">
{{data}}
<br>
<button ng-click="buttonClick()">Clickme!</button>
</div>
问题是:
每当加载页面时,都会触发#/ v1。 如果我点击'Clickme',只是在页面加载后,错误:Scopes.get(...)未定义被触发。
但是,如果我导航到#/ v2然后导航到#/ v1,则会存储范围并且不会触发错误。
routeProvider有问题吗?所有控制器都不会在有载事件中加载?
请帮我解决这个问题。