Reputation: 696
I have three buttons here wish to make $scope. -> q <-
q
as variable. How can I achieve that. This is just a test code my actual problem is based on making q
as variable so please do not suggest any workaround
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = function(q){
$scope.a = "John Doe "; // $scope.q how to make q varibale
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Name: <button ng-click="name('a')" ng-model="name">this is a</button>
<button ng-click="name('b')" ng-model="name">this is b</button>
<button ng-click="name('c')" ng-model="name">this is c</button>
{{a}} via a<br>
{{b}} via b<br>
{{c}} via c<br>
</div>
Upvotes: 1
Views: 2798
Reputation: 6440
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = function(q){
$scope[q] = "John Doe "+ q; // $scope.q how to make q varibale
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Name: <button ng-click="name('a')" ng-model="name">this is a</button>
<button ng-click="name('b')" ng-model="name">this is b</button>
<button ng-click="name('c')" ng-model="name">this is c</button>
{{a}} via a<br>
{{b}} via b<br>
{{c}} via c<br>
</div>
Upvotes: 1
Reputation: 4876
Just add q as a key to scope because $scope in nature is an object
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = function(q){
$scope[q] = "John Doe "; // $scope.q how to make q varibale
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Name: <button ng-click="name('a')" ng-model="name">this is a</button>
<button ng-click="name('b')" ng-model="name">this is b</button>
<button ng-click="name('c')" ng-model="name">this is c</button>
{{a}} via a<br>
{{b}} via b<br>
{{c}} via c<br>
</div>
Upvotes: 4