Ritik Saxena Ritik Saxena - 1 month ago 7
Node.js Question

Controller receives undefined on calling function from factory

The code contains two controllers

teacher
and
render
, the
teacher
controller sets value in factory
share
and
render
calls
get()
function from factory to receive value in
$scope.maincode
but
console.log($scope.maincode)
displays undefined. So,the HTML page does not render the
{{m.code}}
value. Below are the related snippets.

controller-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';
})
}
});


controller-2

app.controller('render',function($rootScope,$scope,share){
$scope.renders = function(){
$scope.m=share.get();
console.log($scope.m);
}
});


factory

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 File

<!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 File-2(which invokes teacher controller)

<!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>



I googled regarding this issue, read the existing questions on similar issues, but couldn't find a solution.
Please help.

Answer

Since you're using two different pages, you either need to use some router, e.g. ngRouter or ui-router, or use localStorage. Here is the example of using localStorage:

app.factory('share', function () {
    function set(obj) {
        localStorage.setItem('share', obj);
    }

    function get() {
        return localStorage.getItem('share');
    }

    return {
        set: set,
        get: get
    }
});