简体   繁体   English

角度 $watch 不起作用

[英]Angular $watch doesn't work

I'm trying to watch a variable which I set in my service, and when it changes - I change a value in the controller, but the watch event isn't firing.我正在尝试观察我在服务中设置的变量,当它发生变化时 - 我更改了控制器中的一个值,但观察事件没有触发。

This is my code:这是我的代码:

var module = angular.module("Test", []);
module.service("testService", TestService);
module.controller("testController", TestController);

function TestService()
{
    var self = this;
    self.Message = "1";
}

TestController.$inject =["$scope", "testService"];
function TestController($scope, testService)
{
    var self = this;
    self.Message = testService.Message;
    $scope.Message = self.Message;

    $scope.$watch("Message", onMessageChange, true)
    self.click = function()
    {
        testService.Message = "2";        
    }

    function onMessageChange(oldVal, newVal)
    {
        self.Message = newVal;
    }
}

and this is the html:这是 html:

<!DOCTYPE html>
<html >
    <head>
        <title>Test</title>

     <script src=".\angular.js"></script>    
     <script src=".\test.js"></script>    
    </head>
    <body ng-app="Test">
   <div  ng-controller="testController as ctrl">
    <button  ng-click="ctrl.click()"> Click </button>
    <span> Message: {{ctrl.Message}}</span>
</div>
    </body>
</html>

Why isn't it working?为什么它不起作用? what am I doing wrong?我究竟做错了什么?

You can watch your service variable like that:您可以像这样查看您的服务变量:

$scope.$watch(function() { return testService.Message;}, onMessageChange, true)

You also need to change oldVal and newVal:您还需要更改 oldVal 和 newVal:

function onMessageChange(newVal, oldVal)
{
    self.Message = newVal;
}

This code was only watching your $scope.Message not your service variable.这段代码只是在看你的 $scope.Message 而不是你的服务变量。

$scope.$watch("Message", onMessageChange, true)

It would only have fired when you change the variable in your click function, like that:它只会在您更改 click 函数中的变量时触发,如下所示:

self.click = function()
{
    $scope.Message = "2";        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM