简体   繁体   English

在angularJs中更改$ scope变量值

[英]Change $scope variable value in angularJs

I have three buttons here wish to make $scope. -> q <- 我在这里有三个按钮,希望使$scope. -> q <- $scope. -> q <- q as variable. $scope. -> q <- q作为变量。 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 这只是一个测试代码,我的实际问题是基于使q为变量,因此请不要提出任何解决方法

 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> 

Just add q as a key to scope because $scope in nature is an object 只需添加q作为范围的键,因为本质上$ scope是一个对象

 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> 

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM