Fred
Fred

Reputation: 21

I need to use a service to store, hold, and make available data across multiple views

This may be very basic but I'm new to angular and am stumped. I have 2 views that need to access the same user input data from a form. Each view has it's own controller.

Here's where I'm at:

JAVASCRIPT

.config(function($routeProvider) {
    $routeProvider
    .when('/view1', {
        templateUrl : 'view1.html',
        controller: 'ctrl1'
    })
    .when('/view2', {
        templateUrl : 'view2.html',
        controller : 'ctrl2'
    })
})

//SERVICE TO HOLD DATA
.service('Data', function() {
    return {};
})

//CONTROLLER 1
.controller('ctrl1', ['$scope', 'Data', function($scope, Data) {
    $scope.data = Data;

    var $scope.initValue = function() {
        $scope.data.inputA = 0; //number
        $scope.data.inputB = 0; //number
    }

    var $scope.onSubmit = function() {
        $scope.data.result = $scope.data.inputA + $scope.data.inputB;
    }
}])

//CONTROLLER 2
.controller('ctrl2', ['$scope', 'Data', function($scope, Data) {
        $scope.data = Data;
    }
}])

HTML (view2.html)

<p>Result is {{data.result}}</p>

This displays nothing, I'm thinking it's because the service or controller resets the values when changing views? Am I just totally wrong for using a service to do this?

Upvotes: 1

Views: 29

Answers (1)

TJL
TJL

Reputation: 179

You have to update the data in the service so that it can be used in another controller:

// define a var container in the service
// you can make it neat by creatin a getter and setter
.service('Data', function() {
    var value = null;
    var setValue = function(val) {
        this.value = val;
    };
    var getValue = function() {
        return this.value;
    };

    return {
        value: value,
        setValue: setValue,
        getValue: getValue,
    };
}

Then in controller 1 you can set the value in the service like so:

//CONTROLLER 1
.controller('ctrl1', ['$scope', 'Data', function($scope, Data) {
    $scope.inputA = 0;
    $scope.inputB = 0;

    $scope.onSubmit = function() {
        $scope.result = $scope.inputA + $scope.inputB;
        Data.setValue($scope.result);
    }
}])

And in controller 2 you can use the value like so:

//CONTROLLER 2
.controller('ctrl2', ['$scope', 'Data', function($scope, Data) {
    $scope.value = Data.getValue();
}])

Hope this will help.

Upvotes: 1

Related Questions