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.

3
  • I think this it's already answered here: get original element from ng-click Commented Nov 8, 2015 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. Commented Nov 8, 2015 at 23:36
  • Then directive is the Angular way Commented Nov 9, 2015 at 0:16

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.