Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to define a function inside Angular-js Directive
    primarykey
    data
    text
    <p>I created a directive for selecting users using bootstrap's drop-down element. as follows.</p> <p><strong>Javascript</strong></p> <pre><code>app.directive('usersDropdown', function(ConfigService,$http) { return { templateUrl: 'app/views/users_dropdown.html', link: function($scope, element, attrs) { }); }; }); </code></pre> <p><strong>users_dropdown.html</strong></p> <pre><code>&lt;div class="btn-group pull-right" &gt; &lt;a class="btn dropdown-toggle" data-toggle="dropdown" href=""&gt; Select User &lt;span class="caret"&gt;&lt;/span&gt; &lt;/a&gt; &lt;ul class="dropdown-menu pull-right align-left" role="menu" aria-labelledby="dropdownMenu"&gt; &lt;li ng-repeat = "userList in userLists"&gt;&lt;a ng-click="getUserDetails('{{userList.SessionId}}')" style="cursor:pointer"&gt;{{userList.UserPartyName}}&lt;/a&gt;&lt;/li&gt; &lt;li ng-hide="userLists" style="cursor:pointer"&gt;&lt;a&gt;No Users&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>I need to create a function <code>getUserDetails</code>, which should be called while clicking on a user from the list. My question is how to define this function inside the directive itself? I wrote it in the controller. But the problem is I am having several controllers. It's not a good practice to write the same function in all controllers. If I can wrote the function common for all controller, that is inside the directive, it will be good. If you have a good solution, let me know that.</p> <hr> <h3>Modification</h3> <p>I modified my directive's js as follows</p> <pre><code>app.directive('usersDropdown', function(ConfigService,$http) { return { templateUrl: 'app/views/users_dropdown.html', link: function($scope, element, attrs) { $scope.getUserDetails = function(user_id){ console.log(user_id); } } }; }); </code></pre> <p>For this I am getting the result in the console as <code>{{userList.SessionId}}</code>. Not the value for that. But when I Inspected the function is passing expected value. <img src="https://i.stack.imgur.com/JYKLl.png" alt="enter image description here"></p> <p>Then why the expected value is not getting inside of that function?</p> <hr> <h3>Solved</h3> <p>I solved the issue by changing my directives html tamplate. I removed <code>'</code> and <code>{{</code> from it as follows.</p> <pre><code>ng-click="getUserDetails(userList.SessionId)" </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload