user2289659
user2289659

Reputation:

Getting Dynamic id (from AngularJS) in getElementByID

I have a clickable drop-down List as following:

<ul class="dropdown">
    <li ng-repeat="item in items" ng-controller="ListCtrl">
        <a href="#" onclick="addWidget();">{{item.name}}</a>
    </li>
</ul>

I have following code of AngularJS in same html page :

<li ng-repeat="item in items" ng-controller="ListCtrl">
    <div id="{{item.itemIndex}}">
     Some Code Here
    </div>
</li>

Now i want to add each div in to my page when click on the list item every time. I calling addWidget() function like this :

<script type="text/javascript">
    function addWidget(){
    document.getElementById('').style.display='block';
    }
</script>

Now My question is if i assign a static id to div and passing it in to getElementByID then it works fine but in the dynamic case how i pass the id so it will work fine in each case ?

Upvotes: 3

Views: 2046

Answers (1)

Derek Ekins
Derek Ekins

Reputation: 11391

You don't want to be adding javascript like that. Here is an example of how to do this:

<body ng-app="myApp">
      <div ng-controller="ListCtrl">
          <ul class="dropdown">
              <li ng-repeat="item in items">
                  <a href="#" ng-click="addWidget(item)">{{item.name}}</a>
              </li>
          </ul>

          <ul>
              <li ng-repeat="item in items" ng-show="item.show">
                  <div>Some Code Here</div>
              </li>
          </ul>
      </div>
</body>

And your controller:

function ListCtrl($scope){
      $scope.items = [{name: 'one'}, {name: 'two'}];
      $scope.addWidget = function(item){
          item.show = !item.show;
      };
};

And finally a working example is here on jsfiddle

Upvotes: 1

Related Questions