AngularJS:在Controller中使用指令元素

arn*_*rts 8 angularjs

我正在创建一个分页应用程序,用户可以在同一个窗口中切换页面(页面显示在彼此之下).每当有人更改页面时,我希望窗口滚动右页

这是我的页面指令:

.directive('page', function () {
    return {
        restrict: "E",
        transclude: true,
        template: '<div ng-transclude></div>',
        link: function(scope, element, attrs) {
            /*
            * Better in controller, now the function has to be evaluated for every directive.
            * */
            scope.$on('pageChanged', function(event, page) {
                if (parseInt(attrs.number) === page) {
                    if (page === 1) {
                        window.scrollTo(100, element[0].offsetTop - 110);
                    }
                    else {
                        window.scrollTo(0, element[0].offsetTop - 60);
                    }
                }
            });
        }
    }
Run Code Online (Sandbox Code Playgroud)

这有效,但现在每个指令都会侦听pageChanged事件并相应地执行操作.我宁愿只在控制器中监听,让控制器将窗口滚动到右侧页面.(这种方式只需要评估一个功能).

$scope.$on('pageChanged', function (event, pageNr) {
            $scope.currentPage = pageNr;
            /*
            * Scroll to the right page directive here
            **/
        });
Run Code Online (Sandbox Code Playgroud)

要做到这一点,我需要访问控制器中的页面元素,有没有办法做到这一点?

我也在寻找一种方法,可以在用户滚动窗口时将currentPage更改为右页.

Ale*_*ias 23

我认为你不应该依赖事件,而是controller在指令对象中添加一个属性并在那里声明指令的控制器.与此类似的东西(尚未测试过):

.directive('page', function () {
    return {
        restrict: "E",
        transclude: true,
        template: '<div ng-transclude></div>',
        controller: function ($scope, $element, $attrs, $transclude, otherInjectables) {
            // Add ng-click="goToPage(n)" directives on your HTML. Those should be inside of the <page> element for this to work.
            $scope.goToPage = function (page) {
                if (page === 1) {
                    window.scrollTo(100, $element[0].offsetTop - 110);
                }
                else {
                    window.scrollTo(0, $element[0].offsetTop - 60);
                }
        },
    }
});
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅有关指令AngularJS文档.