A
A
Anton Agaltsov2016-02-07 21:39:40
JavaScript
Anton Agaltsov, 2016-02-07 21:39:40

How to organize constant data transfer through the factory in AngularJS?

There is a factory (Storage) through which I want to transfer some data entered by the user ($scope.test)
from the controller (View1Ctrl) to the controller (View2Ctrl).
Since this is user-input data, at the time the controller is created, it does not yet exist and the data is transferred when the $scope.testClick1 function is activated, and then $scope.testClick2 - only after that we get the data we need in the second controller (View2Ctrl).
How can this be organized (automated), it is understood that the buttons to send (activating $scope.testClick1 should not be)?

angular.module('myApp',[])
    .factory('Storage', function () {
        var _from = '';
        return {
            setFrom: function (from) {
                _from = from;
            },
            getFrom: function () {
                return _from;
            }
        }
    })

    .controller('View1Ctrl', ['$scope', 'Storage', function($scope, Storage) {
        $scope.test="";
        $scope.testClick1 = function(){
            var tStorage = Storage;
            tStorage.setFrom($scope.test);
            console.log("set", $scope.test);
        };
    }])

    .controller('View2Ctrl', ['$scope', 'Storage', function($scope, Storage) {
        $scope.testClick2 = function(){
            $scope.test = Storage.getFrom();
        };
    }]);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
enchikiben, 2016-02-08
@EnChikiben

watch, for example, hang on the test property, and if they change, the function will be executed

$scope.$watch('test', function(){
  var tStorage = Storage;
  tStorage.setFrom($scope.test);
  console.log("set", $scope.test);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question