3

I have a simple question. I have a <div> and a <button>. I want to access the inner markup of the <div> inside the function I wire with ng-click. How can I do this without jQuery?

<div id = text-entry-view contenteditable="true"></div>

<button class="btn btn-primary btn-block" ng-click = 'sendMsg()'>Send</button>

app.controller('ActiveController', ['$scope', 'contact', '$ManageLoggedInUsername', function($scope, contact, $ManageLoggedInUsername){
    $scope.loggedInUsername = $ManageLoggedInUsername.getUsername();
    $scope.contact = contact;
    $scope.sendMsg = function(){
        //console.log("MSG :: " + <div#text-entry-view.innerHTML>);
    }
}]);

So I want the content of the <div> inside the sendMSG function. Kindly help.

scniro
  • 16,844
  • 8
  • 62
  • 106
Sayantan
  • 329
  • 3
  • 15
  • I think this it's already answered here: [get original element from ng-click](http://stackoverflow.com/questions/23107613/get-original-element-from-ng-click) – maljukan Nov 08 '15 at 23:25
  • IOlander thanks, that solution is good. My DOM is simple but sometimes in complex nested DOM I might need to go too much parent() upwards and then find(). So I was looking for a generic solution. – Sayantan Nov 08 '15 at 23:36
  • Then directive is the Angular way – maljukan Nov 09 '15 at 00:16

1 Answers1

3

Why not just use plain JS in this case? Observe the following...

$scope.sendMsg = function() {
    var markup = document.getElementById('text-entry-view').innerHTML;
    console.log('MSG :: ' + markup);
}

JSFiddle Link - demo


You can also wrap your selector with angular.element() for access to the AngularJS jqLite api e.g.

var markup = angular.element(document.getElementById('text-entry-view')).html()
scniro
  • 16,844
  • 8
  • 62
  • 106
  • scniro thank you, these are nice solutions indeed. But this is just an alternative to the jQuery approach, I mean accessing an element by ID inside any controller. I just read in an Angular tutorial that that approach is not recommended in Angular philosophy, rather we should use Directives. I am a bit confused with Directives. We generally attach Directives to a single DOM element. I was thinking about passing a reference to a DOM element into another element's directive. But don't know how. – Sayantan Nov 08 '15 at 23:40
  • I don't quite see any mention of custom directives in your question. I'd encourage you to accept this answer, which solves your current issue, and formulate a new question - perhaps after trying to mold this into a directive if you have not solved everything on your own at that point – scniro Nov 09 '15 at 04:46