andreaswienes
andreaswienes

Reputation: 3551

Trying to get an element from a template

I am trying to get an element from my template in different ways, but none of them seems to work. This is my code:

<div ng-controller="mainCtrl">       
  <div id="main-content">
     <h1>Main Content</h1>
  </div>
</div>
angular.module("mainModule", [])
    .controller("mainCtrl", ["$scope", "$document", function ($scope, $document) {
      $scope.init = function() {
        var element = angular.element("#main-content");
        console.log(element);
        element = angular.element("main-content");
        console.log(element);
        element = $document.find("#main-content");
        console.log(element);
      }();
    }]);

Maybe one of you got any idea? Thanks for your help!

Upvotes: 1

Views: 54

Answers (2)

harishr
harishr

Reputation: 18055

Try to avoid DOM manipulation when working with angular. But if you still want to do it: below is the way to get hold of the element you need :

       angular.element(document.querySelector('#main-content'))

also you can do it with $element service

        $element.find('#main-content') 

Upvotes: 1

William Lepinski
William Lepinski

Reputation: 917

You should create a Directive for that. AngularJS controller should NEVER reference DOM elements.

Upvotes: 0

Related Questions