user2534381
user2534381

Reputation: 225

Sharing data from directive to controller

I am trying to display the text of link on click event of each link, for that i have written one directive 'showtext' inside which i gets text of the link, howerver i am unable to pass that value through function $scope.$apply("setMessage($element.text)").I also try $scope.message = $element.text inside directive but still its not working.plz help

<div ng-controller="menu">
 <a href="#" showtext>Click</a>
 <a href="#" showtext>Click1</a>
 <a href="#" showtext>Click2</a>
 <button showtext>OK</button>
 <p ng-model="message">You say {{message}}</p>
</div>


var app = angular.module('Demo',[]);

  app.factory('shared',function(){

   });

app.controller('menu',function($scope){
  $scope.message = "" ;
  $scope.setMessage = function(msg){
  $scope.message = msg;
}
});

app.directive('showtext',function(){
return {
    link: function($scope,$element){
        $element.bind('click',function(){
            console.log($element.text());
            $scope.$apply("setMessage($element.text)");
        });
    }
}
});

Upvotes: 0

Views: 81

Answers (1)

If you replace

$scope.$apply("setMessage($element.text)");

with

$scope.$apply(function () {
    $scope.setMessage($element.text())
});

everything works fine.

Upvotes: 3

Related Questions