当范围变量依赖于 AngularJS 中的服务时,何时更新范围变量?

When is a scope variable updated when it depends on a service in AngularJS?

假设我有以下控制器和以下服务:

angular.module('ionicApp').controller("MyCtrl", function($scope, MyService){

    $scope.MyVariable = MyService.getMyVariable();

    $scope.updateMyVariable = function(valueFromHTML){
        MyService.setMyVariable(valueFromHTML);
        $scope.MyVariable = MyService.getMyVariable();
    };
})

.service("MyService", function(){
    this.MyVariable = {};

    this.getMyVariable = function(){
        return this.MyVariable;
    }

    this.setMyVariable = function(value){
        this.MyVariable = value;
        return true;
    }

});

现在让我们采取以下HTML:

<div class="instance-1" ng-controller="MyCtrl">
    <div class="info-from-controller">
        <p>{{MyVariable}}</p>
    </div>
</div>

<div class="instance-2" ng-controller="MyCtrl">
    <button ng-click="updateMyVariable('newValue')">Click me</button>
</div>

让我们说不可能将 2 html 部分放在同一个 div 中,它必须是控制器的不同实例。

如果我按下按钮,从而改变了服务中变量的内容,它是否也会改变两个范围内的变量值,因为它正在调用服务?

我自然会说"only in the scope being in the same instance as the button updating the variable"。 this jsFiddle.

证实了我的印象

但是,我应该如何继续更新第二个范围?有没有办法让控制器 "trigger" 再次检查服务内容?

就我而言,理想的解决方案是能够从HTML 调用服务内容。但是,在尝试了很多事情之后,我不知道该怎么做。

非常感谢任何帮助,谢谢你们!

If I press the button, thus changing the content of the variable in the service, will it also change the value of the variable in both scopes, since it's calling the service ?

没有

服务没有范围,因此摘要周期不会影响您的价值。

其他控制器有自己的范围,你需要广播事件来调用

$scope.MyVariable = MyService.getMyVariable();

或触发摘要周期


作为旁注:

使用同名控制器不是好的做法。使用组件或指令来避免意外行为

当您调用 updateMyVariable 时,它仅在第二个实例中更新 $scope.MyVariable。没错,你应该从模板中调用服务的内容。

Fiddle: http://jsfiddle.net/5rsr2grg/1/

直接从模板调用函数会大大降低应用程序的性能。仅当被调用函数不执行复杂操作时才值得这样做。例如,当它只得到一些 variables/properties/etc 时。但是你的情况一切正常。