更改angularJs中的$ scope变量值

时间:2017-01-31 09:15:45

标签: javascript angularjs cordova ionic-framework

我有三个按钮,希望将$scope. -> q <- q作为变量。我怎样才能做到这一点。这只是一个测试代码,我的实际问题是基于q为变量,所以请不要建议任何解决方法

&#13;
&#13;
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
    }
});
&#13;
<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>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:4)

只需添加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>

答案 1 :(得分: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>

答案 2 :(得分:0)

只需添加q作为$ scope的键Beause $ scope也是一个对象。 试试这段代码: -

控制器

var app = angular.module('myApp', []);
app.controller('ctrl', function($scope) {
    $scope.name = function(q){
    $scope[q] = "Sam"; // now $scope.q will be a varriable
    }
});

在html中: -

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
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>