1

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>

0

2 Answers 2

4

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>

Sign up to request clarification or add additional context in comments.

6 Comments

This is really helpful however there is this problem that after $scope.b is set why the value in $scope.a still exist ? how can i bypass that
Thats the nature of js variables value assigned retains it till memory
The only way is to overwrite it
$scope.name = function(q){ var ar = ["a","b","c"] for(var i=0;i<=ar.length;i++) { $scope[ar[i]]="" } $scope[q] = "John Doe "; } Is this the right way to do it?
yes sure its one of the way to do it if you have just 3 variables its feasible
|
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.