user2464884
user2464884

Reputation:

How to return text to a div in angular js

I have a div in which i want to display a text, from a text-area. How to return the text from a text-area to a div in angularjs. I'm new to angularjs and don't know how it works. Please help.Thank you

Upvotes: 2

Views: 6047

Answers (2)

orlenko
orlenko

Reputation: 1271

As @blaster said, a good way to share data between controllers is to use an Angular service.

A working example can be seen in this fiddle: http://jsfiddle.net/orlenko/5WhKW/

In this example, we define two controllers:

<div ng-controller="SourceController">
    <textarea ng-model="message" ng-change="propagate()"></textarea>
</div>
<div ng-controller="DestinationController">
    <div>{{message}}</div>
</div>

SourceController will be sending notifications about the data changes to DestinationController through a service.

The service uses $rootScope.$broadcast to let the world know it has an update:

myModule.factory('MessageSharing', function ($rootScope, $log) {
    var share = {};

    share.message = '';

    share.broadcast = function (msg) {
        $log.log('broadcasting ' + msg);
        this.message = msg;
        this.broadcastItem();
    };

    share.broadcastItem = function () {
        $log.log('broadcasting  this ' + this.message);
        $rootScope.$broadcast('handleBroadcast');
    };

    return share;
});

Our destination controller will subscribe to the "handleBroadcast" event using $on:

function DestinationController($scope, $log, MessageSharing) {
    $log.log('Initializing DestinationController');
    $scope.message = '';
    $scope.$on('handleBroadcast', function () {
        $log.log('Got the message: ' + MessageSharing.message);
        $scope.message = MessageSharing.message;
    });
}

And finally, the SourceController will publish the updates through the service:

function SourceController($scope, $log, MessageSharing) {
    $log.log('Initializing SourceController');
    $scope.message = '';

    $scope.propagate = function () {
        $log.log('Propagating ' + $scope.message);
        MessageSharing.broadcast($scope.message);
    };
}

Upvotes: 0

Mathew Berg
Mathew Berg

Reputation: 28750

<textarea data-ng-model="myModel"></textarea>    
<div>{{ myModel }}</div>

I really suggest watching some videos as this is a very basic concept for angularjs

Upvotes: 1

Related Questions