控制器与指令一样不能工作



我想通过点击引导模块来完成可滚动的内容。它工作得很好。这是我的指令的以下代码:

'use strict';
angular.module('cbookApp')
        .directive('scrollTo', scrollTo);
scrollTo.$inject = ['$anchorScroll'];
function scrollTo($anchorScroll) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.bind('click', function (event) {
                event.stopPropagation();
                var location = attrs.scrollTo;
                if (scope.vm.isEdit || typeof scope.vm.isEdit =="undefined" ) { 
                    $anchorScroll(location);
                } else {
                    $anchorScroll(location+'1');
                }
            });
        }
    };
}

但唯一的问题是我不确定如何将活动类应用于当前词缀li。这个DEMO方法我发现将active类应用于当前的li,并从其他中移除。它在没有Controller as的情况下工作,但一旦我添加了控制器,因为它停止工作并给出一些范围错误。

var app = angular.module('app', ['directives']);
app.controller('firstController',[function(){
    var vm = this;
    vm.model = { value: 'dsf'};
}]);
angular.module('directives', []).directive('toggleClass', function () {
    var directiveDefinitionObject = {
        restrict: 'A',
        template: '<span ng-click="localFunction()" ng-class="selected"  ng-transclude></span>',
        replace: true,
        bindToController: true,
        scope: {
            model: '='
        },
        transclude: true,
        link: function (scope, element, attrs) {
            scope.localFunction = function () {
                scope.model.value = scope.$id;
            };
            scope.$watch('model.value', function () {
                if (scope.model.value === scope.$id) {
                    scope.selected = "active";
                } else {
                    scope.selected = '';
                }
            });
        }
    };
    return directiveDefinitionObject;
});

你能把这个添加到你的指令中吗?

element.parent().parent().children().each(function() {
    $(this).find('a').removeClass('active');
});
element.addClass('active');

http://jsfiddle.net/hngzxmda/1/

我建议在你的指令中也使用controllera

angular.module('directives', []).directive('toggleClass', function () {
    var directiveDefinitionObject = {
        restrict: 'A',
        template: '<span ng-click="vmd.localFunction()" ng-class="selected"  ng-transclude></span>',
        replace: true,
        bindToController: {
            model: '=',
            $id: '='
        },
        scope: {},
        transclude: true,
        controller: function() {
            var _this = this;
            this.localFunction = function () {
                _this.model.value = _this.$id;
            };
        },
        controllerAs: 'vmd'
    };
    return directiveDefinitionObject;
});

相关内容

最新更新