Accessing data between controller directive and factory

352 views Asked by At

I have created a global variable in factory. And I have accessed the global variable in my controller but upon changing the value in the directive it is unable to update in the controller.

My directive is

myApp.directive('quiz', function(quizFactory) {
return {
    restrict: 'AE',
    scope: {},
    templateUrl: 'templete.html',
    controller: function($scope){
    },
    link: function(scope, elem, attrs,UserService) {
        scope.start = function() {
            UserService.var1=true;
            }
         }  
        };

My Factory is

myApp.factory('UserService', function() {
return {
    var1 : false
    };
 });

My controller is

myApp.controller('LearnSetQue', ['$scope','UserService',
function($scope,UserService){

    $scope.var2=UserService.var1;
    $scope.var3=UserService.var1;
    }
]);

Here start is button function

<button ng-click="start()">Start</button>

Here upon clicking the start button the var1 should become true var1=true,var2=true and var3=true and how can I update that in the controller.

1

There are 1 answers

8
Joao Leal On

First in the service, you should return an object with the properties you want to share across your app:

myApp.factory('UserService', function() {
var properties = { var1: false };
return {
    getProperties : function() { return properties; }
    };
 });

Then in the directive

scope.start = function() {
  UserService.getProperties().var1=true;
}

And in the controller you should have:

myApp.controller('LearnSetQue', ['$scope','UserService',
function($scope,UserService){
    $scope.properties = UserService.getProperties();
]);

And then on the view, just reference the var1 directly

<div>{{ properties.var1 }}</div>