javascript - 仅通过引用绑定(bind)到服务属性?

标签 javascript angularjs

考虑一个服务:

app.service('myService',function(){
    this.strProp = '';
    this.objProp = {
        content: ''
    }
})

还有一个 Controller :

app.controller('myCtrl',function($scope,myService){
    $scope.str = myService.strProp;
    $scope.obj = myService.objProp;
})

还要考虑绑定(bind)两个作用域属性的标记

<input type="text" ng-model="str">
<input type="text" ng-model="obj.content">

当这些值通过用户输入通过 View 更新时,我的服务将仅显示对对象所做的更改,而字符串属性保持为空。

我是否正确地假设这是由于对象是通过引用绑定(bind)而字符串不是?

最佳答案

没错,在您的示例中,strProp 受值约束。

When passing in a primitive type variable like a string or a number, the value is passed in by value. This means that any changes to that variable while in the function are completely separate from anything that happens outside the function.

Passing in an object, however, passes it in by reference. In this case, any property of that object is accessible within the function.

所以,您可能必须像这样更改代码:

$scope.someProp = myService;

然后将其传递到您的 View 中:

<input type="text" ng-model="someProp.strProp">
<input type="text" ng-model="someProp.objProp.content">

关于javascript - 仅通过引用绑定(bind)到服务属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23715022/

相关文章:

Javascript 日期计算

javascript - Vue路由器: TypeError: Cannot read property '$createElement' of undefined

javascript - Angular : Change String to variable

javascript - Angular 过滤掉 ng-repeat 上多个选择中的重复项

angularjs - 如何在 angularjs-dropdown-multiselect 指令中使用 ng-blur 函数

javascript - 为每个 img 分配一个不同的随机类

javascript - 让 Jquery 在 html5 <template> 标签中使用 div

angularjs - 如何在angularJS中检测上传的文件类型

javascript - 数组上的 .indexOf 函数在使用 JavaScript 的 IE7/8 中不起作用

javascript - 测试完成后我应该在作用域上调用 $destroy 吗?