如何将范围模型的引用传递给函数

时间:2015-06-03 12:07:32

标签: javascript angularjs

如何将范围模型的引用传递给函数,我可以在其中编辑它的内容?

例如,我有这样的控制器:

app.controller('MyController', function ($scope) {
    $scope.magic = 123;

    $scope.someMethod = function(model) {
        model = 321;
    }
});

观点:

<div data-ng-controller="MyController as ctrl">
    ...

    <input type="text" data-ng-model="magic">

    <button type="button" data-ng-click="someMethod(magic)">
</div>

现在,当我点击按钮时,它几乎可以正常工作,但在someMethod之后,实际的$ scope.magic没有改变,它仍然是321.所以显然someMethod创建了一个副本模型,而不是参考。如何获得参考?

1 个答案:

答案 0 :(得分:0)

将您的someMethod更改为以下内容:

$scope.someMethod = function(model) {
    model.magic = 321;
}

// Or accepting a new value
$scope.anotherMethod = function(model, value) {
    model.magic = value;
}

HTML:

<input type="text" data-ng-model="model.magic">
<button type="button" data-ng-click="someMethod(model)">Do Some Magic!</button>

<!-- Or with passing a new value -->
<button type="button" data-ng-click="anotherMethod(model, '123')">Do Some Magic!</button>

http://feeds.bbci.co.uk/news/rss.xml