代码包含两个控制器teacher
和render
,teacher
控制器设置工厂share
和render
调用get()
函数的值工厂要在$scope.maincode
中接收值,但console.log($scope.maincode)
显示未定义。因此,HTML页面不会呈现{{m.code}}
值。以下是相关摘录。
控制器-1
app.controller("teacher",function($rootScope,$scope,$http,$location,$window,share){
$scope.load = function(){
$http.get('/getcode').success(function(data){
if(data.length>0){
$scope.message = "";
$scope.codes = data;
console.log($scope.codes);
}
else {
$scope.codes="";
$scope.message = "No code submissions yet";
}
})
$scope.send = function(id){
console.log(id);
$http.get("/code/"+id).success(function(data){
share.set(data);
$window.location.href ='/code';
})
}
});
控制器-2
app.controller('render',function($rootScope,$scope,share){
$scope.renders = function(){
$scope.m=share.get();
console.log($scope.m);
}
});
工厂
app.factory('share',function(){
var data = {};
this.set = function(obj){
this.data = obj;
console.log(this.data);
}
this.get = function(){
return this.data;
}
return {
set: this.set,
get: this.get
}
});
HTML文件
<!DOCTYPE html>
<html>
<head>
<base href="/" />
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script src="js/angular-resource.min.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="app" ng-controller="render">
<div data-ng-init="renders()">
{{m.code}}
</div>
<a href="/logout">Logout</a>
</body>
</html>
HTML文件-2(调用教师控制器)
<!DOCTYPE html>
<html>
<head>
<base href="/" />
<script src="/js/angular.min.js"></script>
<script src="/js/angular-route.min.js"></script>
<script src="/js/angular-resource.min.js"></script>
<script src="/js/app.js"></script>
</head>
<body ng-app="app">
<div data-ng-controller="teacher">
<div data-ng-init="load()">
<div ng-repeat="code in codes" ng-show="codes">
<a href ng-click="send(code.id)">{{code.title}}</a>
</div>
</div>
<div>
<h4>{{message}}</h4>
</div>
</div>
<a href="/logout">Logout</a>
</body>
我搜索了关于这个问题,阅读有关类似问题的现有问题,但找不到解决方案。 请帮忙。
答案 0 :(得分:1)
由于您使用的是两个不同的页面,因此您需要使用某些路由器,例如ngRouter
或ui-router
,或使用localStorage
。以下是使用localStorage
:
app.factory('share', function () {
function set(obj) {
localStorage.setItem('share', obj);
}
function get() {
return localStorage.getItem('share');
}
return {
set: set,
get: get
}
});
答案 1 :(得分:0)
在您展示render
和m.code
时,您未收到承诺的结果。
为了解决这个问题,在broadcast
控制器中获取get请求的值后,只需teacher
到范围。
`$rootScope.$broadcast('data-received');`
现在,您可以在渲染controller
$scope.$on('data-received', function(event, args) {
$scope.m=share.get();
});
控制器1
app.controller("teacher",function($rootScope,$scope,$http,$location,$window,share){
$scope.send = function(id){
console.log(id);
$http.get("/code/"+id).success(function(data){
share.set(data);
$rootScope.$broadcast('data-received');
$window.location.href ='/code';
})
}
});
控制器-2
app.controller('render',function($rootScope,$scope,share){
$scope.renders = function(){
$scope.m=share.get();
console.log($scope.m);
}
$scope.$on('data-received', function(event, args) {
$scope.m=share.get();
});
});
这可以解决您的问题。