我已经看到了两种方法来做到这一点。查看服务/控制器:
var app = angular.module('myApp', []);
app.service('user', function() {
this.loggedIn = false;
this.logIn = function() {
this.loggedIn = true;
};
this.logOut = function() {
this.loggedIn = false;
};
});
function Ctrl1($scope, user) {
$scope.user = user;
}
function Ctrl2($scope, user) {
$scope.loggedIn = user.loggedIn;
// Proxy functions
// This wont work because of binding:
// $scope.logIn = user.logIn;
// $scope.logOut = user.logOut;
// This works
$scope.logIn = function() {
user.logIn();
};
$scope.logOut = function() {
user.logOut();
};
// This also works:
// $scope.logIn = user.logIn.bind(user);
// $scope.logOut = user.logOut.bind(user);
$scope.$watch(function() {
return user.loggedIn;
}, function(value) {
$scope.loggedIn = value;
});
}
和 HTML:
<div ng-controller="Ctrl1">
<h2>Ctrl1: Access the user service directly</h2>
<div ng-show="user.loggedIn">
Logged In
<button ng-click="user.logOut()">Log Out</button>
</div>
<button ng-show="!user.loggedIn" ng-click="user.logIn()">Log In</button>
</div>
<hr />
<div ng-controller="Ctrl2">
<h2>Ctrl2: Proxy via the controller</h2>
<div ng-show="loggedIn">
Logged In
<button ng-click="logOut()">Log Out</button>
</div>
<button ng-show="!loggedIn" ng-click="logIn()">Log In</button>
</div>
直播:http: //jsfiddle.net/h6AR4/
将服务直接添加到范围感觉不对,但会导致控制器代码更清晰。
代理所有功能会导致控制器代码混乱。
是否有明确的“角度方式”?