Javascript 监视函数从服务返回不起作用,但作用域函数起作用
我的服务功能有问题 如果我通过服务在视图中使用函数,如果返回更改,它将不会更新 但如果我使用一个在控制器中声明的函数,它就会工作 为什么? 第一个示例,不工作,服务功能: 第二个示例,工作,控制器功能:Javascript 监视函数从服务返回不起作用,但作用域函数起作用,javascript,angularjs,angularjs-scope,Javascript,Angularjs,Angularjs Scope,我的服务功能有问题 如果我通过服务在视图中使用函数,如果返回更改,它将不会更新 但如果我使用一个在控制器中声明的函数,它就会工作 为什么? 第一个示例,不工作,服务功能: 第二个示例,工作,控制器功能: 谢谢你的建议如果我删除变量前面的$ 和模板 <div ng-controller="MyCtrl"> Hello, {{name}}!<br /> You're logged <p ng-show="service.checkLogge
谢谢你的建议如果我删除变量前面的$ 和模板
<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>
你好,{{name}}
你被记录了
中的
退出
.
{{LoginTxt}}
学习AngularJS语法非常有趣:)
谢谢。如果您的模板中只有
服务
,为什么要改为服务
?您在控制器中称之为服务
。(你应该在你的问题中包括模板,因为它们对解决这个问题很重要。)我想我必须在模板中的服务之前使用$。但是如果我试一下你说的话,它是有效的-。-:D有趣!谢谢
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;
};
}
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>