简体   繁体   中英

Update ng-model from Angular service

I have angular application and textarea in it:

<textarea id="log_text_area" readonly>{{logger}}</textarea>

Also i have a Logger service which must update this textarea .

angular.module('app').factory('Logger', [function(){
    var logger = {};

    //
    // Write log
    //
    logger.log = function(log_area, arguments){
        // get current date
        var date = new Date();
        // log message
        var message = '';

        // traverse object and collect log message
        for (var i = 0; i < arguments.length; i++) {
            message += arguments[i] + " ";
        }

        console.log(log_area);

        // check log area
        if (log_area != undefined){
            // log value
            var value = "[" + date + "}] " + message + "\n";
            value += log_area;
            log_area = value;
        }
    };

    // return logger
    return logger;
}]);

Now i want to update my textarea from controller:

function MyController($scope, Logger) {     
    $scope.logger = '';

    Logger.log($scope.logger, 'Logs Logs Logs');
}

But it doesn't update. How to update textarea from angular service?

Thank you.

Have your log function return the text only and assign the returned value to your $scope property in the controller.

$scope.logger = Logger.Log('log, log log');

Or you could call $scope.$apply(); after the log() call, but approach numero uno is cleaner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM