1

我正在尝试创建一个服务来存储教程是否处于活动状态,以便我可以在不同的控制器之间共享该信息。我还在为服务创建一个范围,以便我可以观察值何时发生变化。有没有办法将服务中创建的范围暴露给控制器?

我已经尝试过 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();
        };
    }]);

JS小提琴

似乎 2 不是最佳实践,因为它在表达式中使用函数,但 1 似乎暴露太多?或者也许我应该使用控制器?

4

1 回答 1

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();
    };
});

小提琴

于 2013-06-06T17:33:29.393 回答