我有一个范围变量,默认值为false
。
我希望将此变量传递给函数以将其值修改为true
。
但是,由于JavaScript中params的传递是有价值的,所以无法完成。
这是我尝试做的简单代码:
myapp.controller('PersonCtrl', function ($scope) {
$scope.step = false;
change($scope.step);
console.log($scope.step);
});
change = function(step){
step = true;
}
的jsfiddle:
http://jsfiddle.net/SNF9x/177/
我该如何解决这个问题?
答案 0 :(得分:5)
您可以将持有原始对象的对象传递给您的更改功能:
myapp.controller('PersonCtrl', function ($scope) {
$scope.step = false;
change($scope);
console.log($scope.step);
});
change = function(obj){
obj.step = true;
}
您可以通过事件传递要更改的变量的名称:
myapp.controller('PersonCtrl', function ($scope) {
$scope.step = false;
change($scope, 'step');
console.log($scope.step);
});
change = function(obj, prop){
obj[prop] = true;
}
答案 1 :(得分:3)
您无法通过引用在JS中传递变量,但您可以通过引用传递对象,然后修改属性,如下所示......
myapp.controller('PersonCtrl', function ($scope) {
$scope.step = false;
change($scope);
console.log($scope.step);
});
change = function($scp){
$scp.step = true;
}
<强>的jsfiddle:强>
答案 2 :(得分:1)
在您的OP中,您尝试更改基本类型的值:
var o = {
b: true
};
changeValue(o.b);//pass a primitive type to the function
console.log(o.b);//print out true because is primitive type and all primitive types pass by value
function changeValue(b) {
b = false;
}
一种解决方案是将对象$scope
传递给函数:
var myapp = angular.module('myapp', []);
myapp.controller('PersonCtrl', function($scope) {
$scope.step = false;
change($scope);
console.log($scope.step);//prints out true
});
change = function(obj) {
obj.step = true;
}