我有以下看法:
<input ng-model="something" />
<button ng-click="modify(something)">Modify</button>
Controller 中的这个方法:
$scope.modify = function (value) {
value = value + " and this text";
};
但是,modify
方法不执行任何操作。
我想做的是创建一个函数,可以通过参数修改模型中的对象。我的意思是,函数 x
通过参数接收对象,并且在该函数内部,可以修改该对象(来自模型)。
我怎样才能做到这一点?
参见 this fiddle 供引用。
最佳答案
已经晚了,所以我可能会错过明显的,但是......
由于您传递的是字符串,因此它是按值而不是引用传递的。所以我更改了您的 ng-click 以引用范围内的对象,而不是值本身。
然后修改函数引用作用域而不是变量本身。
查看
<div ng-app>
<div ng-controller="SomeCtrl">
<input ng-model="something" />
<button ng-click="modify('something')">Modify</button>
</div>
</div>
Controller
function SomeCtrl($scope) {
$scope.something = "test";
$scope.modify = function (value) {
$scope[value] = $scope[value] + " and this text";
};
}
关于javascript - angular.js - 通过参数将模型中的值修改为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21271429/