0

I have the following HTML:

<div class="custom-select">
    <div class="custom-select-placeholder">
        <span id="placeholder-pages">Show all posts</span> 
    </div>
    <ul class="custom-select-list animate-show no-padding no-margin" >
        <li ng-click="selectItem($event)">Show all posts</li>
        <li ng-click="selectItem($event)">Events</li>
        <li ng-click="selectItem($event)">Files</li>
        <li ng-click="selectItem($event)">Pictures</li>
        <li ng-click="selectItem($event)">Thoughts</li>
    </ul>
</div>

When I click on a 'li' item, I need to fetch its innerHTML and set the innerHTML of the span having its id as 'placeholder-pages' to the value fetched.

For this I wrote the following function in my controller:

$scope.selectItem = function(evt) {
        var selected = evt.target.innerHTML; //working
        var placeholder = document.getElementById('placeholder-pages'); //working
        placeholder.innerHTML = selected; //not working
}

In the function I am able to get the innerHTML of the 'li' selected and also the 'placeholder-pages' div. But I cannot set the div's innerHTML. I am not getting any error. Nothing happens.

2
  • 2
    wish i could help more, but you should not need innerHTML if you are working with angular - you are making things harder for your self than you need to Commented Oct 7, 2015 at 9:26
  • Yes, actually I solved it using ng-bind, but I was curious why the above code doesn't work. Commented Oct 7, 2015 at 9:28

3 Answers 3

1

I solved it by using ng-bind.

HTML:

<div class="custom-select-placeholder">
    <span id="placeholder-pages" ng-bind="selected_option"></span> //set html using ng-bind
</div>

Controller:

$scope.selected_option = 'Show all posts';

$scope.selectItem = function(evt) {
        var selected = evt.target.innerHTML; 
        $scope.selected_option = selected;
}

I guess this is a more 'Angular' way of doing things as suggested by @Simon.

Sign up to request clarification or add additional context in comments.

Comments

0

As Simon already said you should use ng-bind instead. As a rule of thumb all DOM access and manipulation belong to a directive link function.

BTW. Your code works fine: http://plnkr.co/edit/PB5P2dhDD836mkssVlOo?p=preview

1 Comment

yes I used ng-bind instead. Also, I have no idea why it is not working in my code. :/
0

Your code works fine. Checked it in Chrome (v45) , FF (v39) and even IE9 - everything works perfectly (Angular version is 1.3.14), placeholder properly receives the innerHTML data and displays it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.