Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I dynamically define a function to call with ng-click in AngularJS directive template
    text
    copied!<p>I'm trying to dynamically generate form inputs and an associated action menu based on the model. I'm able to pass the field to be used and the menu, but I can't figure out how to configure ng-click to call the appropriate function defined in the model. See fiddle : <a href="http://jsfiddle.net/ahonaker/nkuDW/">http://jsfiddle.net/ahonaker/nkuDW/</a></p> <p>HTML:</p> <pre><code>var myApp = angular.module('myApp',[]); myApp.directive('myDirective', function($compile) { return { restrict: "E", replace: true, scope : { field: '=', label: '=', menu: '=' }, link: function (scope, element, attrs) { element.html('{{label}}: &lt;input ng-model="field"&gt; &lt;ul ng-repeat="item in menu"&lt;li&gt;&lt;a ng-click="item.func"&gt;{{item.title}}&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;'); $compile(element.contents())(scope); } } }); //myApp.factory('myService', function() {}); function MyCtrl($scope) { $scope.status = 'You have not picked yet'; $scope.menu = [ { "title" : "Action 1", "func" : "ActionOne()"}, { "title" : "Action 2", "func" : "ActionTwo()"}, ] $scope.fieldOne = "I am field 1"; $scope.fieldTwo = "I am field 2"; $scope.ActionOne = function() { $sopce.status = "You picked Action 1"; } $scope.ActionOne = function() { $sopce.status = "You picked Action 2"; } } </code></pre> <p>JS:</p> <pre><code>&lt;div ng-app = "myApp"&gt; &lt;div ng-controller="MyCtrl"&gt; &lt;ul&gt; &lt;p&gt;&lt;my-directive field="fieldOne" label="'Field 1'" menu="menu"&gt;&lt;/my-directive&gt;&lt;/p&gt; &lt;p&gt;&lt;my-directive field="fieldTwo" label="'Field 2'" menu="menu"&gt;&lt;/my-directive&gt;&lt;/p&gt; &lt;/ul&gt; Hello, {{status}}! &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Any help would be appreciated. I've tried the following ng-click approaches in the directive</p> <pre><code>ng-click={{item.func}} ng-click="item.func" ng-click="{{item.func}}" </code></pre> <p>What am I doing wrong? Or is there a better way to do this (the menu structure including the functions to be called have to come from the model in order for me to build a generic form generation capability).</p>
 

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