我的服务功能有问题。
如果我通过服务在视图中使用某个函数,那么如果返回更改则不会更新。
但是,如果我使用在控制器中声明的函数,它可以工作。
为什么吗
第一个例子,不工作,服务功能:
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;
};
}
感谢您的任何想法!
答案 0 :(得分:0)
如果我删除变量前面的$,它会起作用。
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。