监视函数从服务返回不起作用,但作用域函数起作用

Watching function return from service not working but a scope function works

本文关键字:函数 作用域 起作用 返回 服务 监视 不起作用      更新时间:2023-09-26

我的服务函数有问题。

如果我通过服务在视图中使用函数,那么如果返回值发生更改,它就不会更新。

但如果我使用一个在控制器中声明的函数,它就可以工作。

为什么

第一个例子,不工作,服务功能:

https://jsfiddle.net/xrzr457v/

var myApp = angular.module('myApp', []),
    test = null;
myApp.factory('myService', function() {
    return {
        checkLoggedIn: function()
        {
            return test == null;
        }
    }
});
function MyCtrl($scope, myService)
{
    $scope.name = 'Superhero';
    $scope.service = myService;
    $scope.LoginTxt = 'Login';
    $scope.login = function()
    {
        $scope.LoginTxt = 'You should be logged in and the texts should be moved!';
        test = true;
    };
}

第二个例子,工作,控制器功能:

https://jsfiddle.net/t3nyejLy/

var myApp = angular.module('myApp', []),
    test = null;
function MyCtrl($scope)
{
    $scope.name = 'Superhero';
    $scope.checkLoggedIn = function()
    {
        return test == null;
    };
    $scope.LoginTxt = 'Login';
    $scope.login = function()
    {
        $scope.LoginTxt = 'You should be logged out and the texts should be moved!';
        test = true;
    };
}

谢谢你的想法

如果我删除变量前面的$,它就会起作用。

https://jsfiddle.net/xrzr457v/2/

var myApp = angular.module('myApp', []),
    test = null;
myApp.factory('myService', function() {
    return {
        checkLoggedIn: function()
        {
            return test == null;
        }
    }
});
function MyCtrl($scope, myService)
{
    $scope.name = 'Superhero';
    $scope.service = myService;
    $scope.LoginTxt = 'Login';
    $scope.login = function()
    {
        $scope.LoginTxt = 'You should be logged in and the texts should be moved!';
        test = true;
    };
}

和模板

<div ng-controller="MyCtrl">
    Hello, {{name}}!<br />
    You're logged
    <p ng-show="service.checkLoggedIn()">in</p>
    <p ng-hide="service.checkLoggedIn()">out</p>
    .
    <br /><br />
    <button ng-click="login()" ng-show="service.checkLoggedIn()">{{ LoginTxt }}</button>
</div>

学习AngularJS语法非常有趣:)

感谢Kevin B.