我正在尝试创建一个服务来存储教程是否处于活动状态,以便我可以在不同的控制器之间共享该信息。我也在为服务创建一个范围,这样我就可以在价值变化时观察。有没有办法将服务中创建的范围暴露给控制器?
我尝试过1)使用函数公开scope
变量和2),但似乎还有另一种方法。有吗?
HTML
<div ng-app="App">
<h2>As variable</h2>
<div ng-controller="tutorialController">
<button ng-click="toggleActive()">Toggle</button>
<div ng-show="tutorial.scope.isActive">Tutorial</div>
<div ng-bind="tutIsActive"></div>
</div>
<hr/>
<div ng-controller="tutorialController2">
<h2>As function</h2>
<button ng-click="toggleActive()">Toggle</button>
<div ng-show="tutorial.isActive()">Tutorial</div>
<div ng-bind="tutIsActive"></div>
</div>
</div>
JS
var App = angular.module('App', [])
// 1: As variable
.factory("Tutorial", ["$rootScope", function($rootScope) {
var scope = $rootScope.$new();
scope.isActive = true;
scope.$watch('isActive', function() {
console.log("1: isActive changed: " + scope.isActive);
});
return {
scope: scope
};
}])
.controller('tutorialController', ["$scope", "Tutorial", function($scope, Tutorial) {
$scope.tutorial = Tutorial;
$scope.tutIsActive = $scope.tutorial.scope.isActive;
$scope.toggleActive = function() {
console.log("1: toggleActive");
$scope.tutorial.scope.isActive = !$scope.tutorial.scope.isActive;
$scope.tutIsActive = $scope.tutorial.scope.isActive;
};
}])
// 2: As function
.factory("Tutorial2", ["$rootScope", function($rootScope) {
var scope = $rootScope.$new();
scope.isActive = true;
scope.$watch('isActive', function() {
console.log("2: isActive changed: " + scope.isActive);
});
return {
isActive: function() {
return scope.isActive;
},
toggle: function() {
scope.isActive = !scope.isActive;
}
};
}])
.controller('tutorialController2', ["$scope", "Tutorial2", function($scope, Tutorial) {
$scope.tutorial = Tutorial;
$scope.tutIsActive = $scope.tutorial.isActive();
$scope.toggleActive = function() {
console.log("2: toggleActive");
$scope.tutorial.toggle();
$scope.tutIsActive = $scope.tutorial.isActive();
};
}]);
似乎2不是最佳做法,因为它使用的是function within an expression,但是1似乎暴露了太多?或者也许我应该使用控制器?
答案 0 :(得分:2)
您不需要公开范围。只需将注入的教程附加到您需要的控制器范围:
var App = angular.module('App', [])
App.factory("Tutorial", function() {
return {
isActive: true,
toggleActive: function() {
this.isActive = !this.isActive;
}
};
});
App.controller('tutorialController', function($scope, Tutorial) {
$scope.tutorial = Tutorial;
$scope.toggleActive = function() {
$scope.tutorial.toggleActive();
};
});