角度服务更新变量但视图不更新

时间:2014-08-20 20:39:14

标签: angularjs

这是我的问题的一个方面。 http://jsfiddle.net/angularismyman/pc5tq0wa/基本上我的控制器2正在调用一个服务,该服务正在更新我的控制器1的视图被绑定到的变量,但视图没有更新。

我的Html:

<div ng-app="myApp">
    <div ng-controller="FirstCtrl">
        Controller 1: <br/>
        {{text}}
    </div>
    <br/>
    <br/>
    <br/>
    <div ng-controller="SecondCtrl">
        Controller 2: <br/>
        <button ng-click="updateView()">Change text in controller 1 to Jelly</button>
    </div>
</div>

我的服务和两个控制器:

var myApp = angular.module('myApp', []);

myApp.service('Session', function () {

    var value = "peanut butter";

    this.value = value;

    this.changeTest = function(){
        alert("changing to jelly!");
        alert("our current value is: "+value);
        value = "jelly";
        alert("our new value is: "+value);
        alert("why isn't text updating in controller 1?");
    }

    return this
});

function FirstCtrl($scope, Session){
  $scope.text = Session.value;
}

function SecondCtrl($scope, Session){
    $scope.updateView = function(){
        Session.changeTest();
    }
}

0 个答案:

没有答案