2017-01-31 121 views
1

我在這裏有三個按鈕,希望使$scope. -> q <-q爲變量。我怎樣才能做到這一點。這僅僅是一個測試代碼我實際的問題是基於使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>

回答

4

只需加Q作爲重點範圍,因爲在自然界$範圍對象

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>

+0

這是真正有用的卻沒有這個問題,經過$ scope.b設置在$爲何值scope.a還存在嗎?我怎麼能繞過 – sam

+0

那是JS的變量值分配性質保留它,直到內存 –

+0

有沒有解決方法是不要發生呢? – sam

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>

0

只需加Q作爲重點$範圍Beause $範圍也是一個對象。 試試這個代碼: -

控制器

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> 
相關問題