在AngularJS中,作用域属性可以通过引用来传递吗?

Can scope properties be passed by reference in AngularJS?

本文关键字:引用 可以通过 AngularJS 作用域 属性      更新时间:2023-09-26

下面的代码会在AngularJS控制器中正常工作吗?

 updateProperty($scope.property1);
 var updateProperty=function(property){
    property+=1;
    /* Will the above line change $scope.property1? */
 }

如果上面的语法不起作用,是否有另一种方法来创建一个可以用来更新任何作用域属性的泛型函数?

不能通过引用传递主类型。试着传递object:

$scope.property1 = {
  value: 1
};
updateProperty($scope.property1);
var updateProperty=function(property){
  property.value += 1;
}

假设它运行在一个注入了$scope的控制器中,你可以这样做:

updateScopeProperty("property1");
function updateScopeProperty(propertyName) {
    $scope[propertyName] += 1;
}