2

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

2 Answers2

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

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

Mathew Berg
  • 28,625
  • 11
  • 69
  • 90
  • Thanks for your answer. But, i have a div which is in other controller. So, i want to display the text in div, which is in other controller. Thank You –  Jun 14 '13 at 13:48
  • Provide a jsFiddle please. – Mathew Berg Jun 14 '13 at 14:22
  • 1
    Oh, sorry. I'm a beginner. I haven't used jsFiddle. Do you mean code ? –  Jun 14 '13 at 14:38
  • To share state across multiple controllers, use an Angular service. Then from either controller you can bind to the same thing, as in "myService.myModel" . . . http://stackoverflow.com/questions/15100020/using-angular-service-to-share-data-between-controllers – blaster Jun 14 '13 at 14:43
0

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);
    };
}
orlenko
  • 1,251
  • 8
  • 11