Jason
Jason

Reputation: 129

Generic method to set models passed as arguments, Angular JS

I wanted to write a generic method to set different models passed as a variable to the function on ng-click, googled a lot but found nothing which is useful, here is my code

<span class="fa fa-star " ng-click="setClassJsn(1, 'present')" id='present'></span>
<span class="fa fa-star " ng-click="setClassJsn(1, 'clarity')" id='present'></span>

<input type="text" ng-model="present" />
<input type="text" ng-model="clarity" />

I wanted to translate the "e" to the model name and set it accordingly.

$scope.setClassJsn = function(value, e) {

    alert("hai this is setting class");
    console.log(e);

    $scope."e" = value;
};      

Please note that i know $scope."e" = value; this statement is wrong just to understand i have given the quotes.

Upvotes: 1

Views: 59

Answers (1)

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

You can try $scope[e] = value.

angular.module("app", []).controller("ctrl", function($scope) {
  $scope.setClassJsn = function(value, e) {    
    console.log(e);
    $scope[e] = value;
  }
  
  $scope.displayClassJsn = function(e) {
    console.log($scope[e]);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <span class="fa fa-star " ng-click="setClassJsn(1,'present')" id='present'>Span 1</span>
  <span class="fa fa-star " ng-click="setClassJsn(1,'clarity')" id='present'>Span 2</span>

  <input type="text" ng-model="present" />
  <input type="text" ng-model="clarity" />
  
  <br/>
  <button ng-click="displayClassJsn('present')">Show 'present'</button>
  <button ng-click="displayClassJsn('clarity')">Show 'clarity'</button>
</div>

Upvotes: 1

Related Questions