Novalis
Novalis

Reputation: 81

set data in factory and bind it to controller

goal: show an error in controller (errorCtrl), which can be set up in mutiple other controllers (i.e. modulCtrl)

i try this by setting up a service (ErrorConsole).

logViewApp.service('ErrorConsole', function () {
    this.errorMsg = 'no error';
    return {
        error: this.error,
        setError: function(data){
            this.error = data;
        }
    }
});

it is easy to retrive the data from the service

js:

logViewApp.controller('errorConsoleCtrl', function ($scope, ErrorConsole) {
    $scope.error = ErrorConsole.errorMsg;
});

html:

<nav class="navbar navbar-default navbar-fixed-bottom" role="navigation" ng-controller="errorConsoleCtrl">
        <div class="container-fluid text-danger">
            ERROR:{{msg}}<br>
            <span >Query:{{query}}</span><br>
            test:{{testdata}}

        </div>
    </nav>

but i can set the data in factory, but it wont display in errorConsoleCtrl

logViewApp.controller('modulCtrl', function( $scope, $http, $routeParams, ErrorConsole ){
    $scope.moduleName = $routeParams.modulId;

    var postData = {
        task: 'loadLogsByModul',
        modul: moduleName,
        limit: 100
    }

    $http.post('data/log.php', postData).success(function (ret) {
        if (!ret.error) {
              // ...do stuff
        }
        else {
            ErrorConsole.setError('fatal error');
            console.log( ErrorConsole );
        }
    });

});

first question: is this the right approach? second question: why is this not working? is a dependency injected factory still subject of controller scope?

Upvotes: 0

Views: 61

Answers (1)

Chandermani
Chandermani

Reputation: 42669

The service recipe is invoked like a constructor function, so there is no point doing a return. The service should be written as

logViewApp.service('ErrorConsole', function () {
    this.errorMsg = 'no error';
    this.setError: function(data){
            this.errorMsg = data;
        }
    }
});

Upvotes: 1

Related Questions