角度服务大规模范围

时间:2016-02-13 17:49:56

标签: angularjs angular-services

我的slugify功能运行顺利。

困扰我的是必须在所有控制器中重复功能代码。

有可能转换成服务,或者我只写一次这个功能吗?

今天使用这种形式:

<md-input-container class="md-accent">
    <label >Digite o título do Produto</label>
    <input ng-model="product.title" ng-change="slugify(product.title)">
</md-input-container>

<md-input-container class="md-accent">
    <label>Link permanente</label>
    <input ng-model="product.slug" disabled>
</md-input-container>

我的slugify功能:

$scope.slugify = function(slug){
    var makeString = function(object) {
        if (object === null) {
            return '';
        }
        return '' + object;
    };

    var from  = 'ąàáäâãåæăćčĉęèéëêĝĥìíïîĵłľńňòóöőôõðøśșšŝťțŭùúüűûñÿýçżźž',
        to    = 'aaaaaaaaaccceeeeeghiiiijllnnoooooooossssttuuuuuunyyczzz',
        regex = new RegExp('[' + from + ']', 'g');

    slug = makeString(slug).toString().toLowerCase().replace(regex, function (c){
        var index = from.indexOf(c);
        return to.charAt(index) || '-';
    }).replace(/[^\w\-\s]+/g, '').trim().replace(/\s+/g, '-').replace(/\-\-+/g, '-');

    $scope.product.slug = slug;
};

解决方案! FACTORY:

.factory('slugify', function() {
    var self = this;
    self.generate = function(slug){
        var makeString = function(object) {
            if (object === null) {
                return '';
            }
            return '' + object;
        };

        var from  = 'ąàáäâãåæăćčĉęèéëêĝĥìíïîĵłľńňòóöőôõðøśșšŝťțŭùúüűûñÿýçżźž',
            to    = 'aaaaaaaaaccceeeeeghiiiijllnnoooooooossssttuuuuuunyyczzz',
            regex = new RegExp('[' + from + ']', 'g');

        slug = makeString(slug).toString().toLowerCase().replace(regex, function (c){
            var index = from.indexOf(c);
            return to.charAt(index) || '-';
        }).replace(/[^\w\-\s]+/g, '').trim().replace(/\s+/g, '-').replace(/\-\-+/g, '-');
        return slug;
    };
    return self;
});

在控制器中:

$scope.slugIt = function(title){
    $scope.product.slug = slugify.generate(title);
};

在观点中:

<input ng-model="product.title" ng-change="slugIt(product.title)">

2 个答案:

答案 0 :(得分:1)

我不知道你的具体要求。但是,你可以编写类似这样的服务

angular.module('app').service('slugService',
    function () {
        function serviceInstance() {
            var services = {
                slugify: slugify,
                slug: slug
            };

            var slug = null;

            function slugify(slug) {
                var makeString = function (object) {
                    if (object === null) {
                        return '';
                    }
                    return '' + object;
                };

                var from = 'ąàáäâãåæăćčĉęèéëêĝĥìíïîĵłľńňòóöőôõðøśșšŝťțŭùúüűûñÿýçżźž',
                    to = 'aaaaaaaaaccceeeeeghiiiijllnnoooooooossssttuuuuuunyyczzz',
                    regex = new RegExp('[' + from + ']', 'g');

                this.slug = makeString(slug).toString().toLowerCase().replace(regex, function (c) {
                        var index = from.indexOf(c);
                        return to.charAt(index) || '-';
                    })
                    .replace(/[^\w\-\s]+/g, '')
                    .trim().replace(/\s+/g, '-')
                    .replace(/\-\-+/g, '-');

            }

            return services;
        }

        return new serviceInstance();
    }
);

//inject the service in your controller
angular.module('app').controller('urController', function(slugService){


}

and use it in your view

ng-change(slugService.slugify(product.title))

ng-model(slugService.slug)  //probably need to use ng-init as well

//假设每页使用一次服务

答案 1 :(得分:1)

您可以创建一个使用该服务生成slug的指令。

.factory('slugger', function slugger() {
    return {
        generateSlug: generateSlug
    };

    function generateSlug(input) {
        var from = 'ąàáäâãåæăćčĉęèéëêĝĥìíïîĵłľńňòóöőôõðøśșšŝťțŭùúüűûñÿýçżźž';
        var to = 'aaaaaaaaaccceeeeeghiiiijllnnoooooooossssttuuuuuunyyczzz';
        var regex = new RegExp('[' + from + ']', 'g');

        input = makeString(input).toString().toLowerCase().replace(regex, function (c) {
            var index = from.indexOf(c);
            return to.charAt(index) || '-';
        }).replace(/[^\w\-\s]+/g, '').trim().replace(/\s+/g, '-').replace(/\-\-+/g, '-');

        return input;
    }

    function makeString(object) {
        if (object === null) {
            return '';
        }

        return '' + object;
    }
})

.directive('slugInput', function (slugger) {
    return {
        require: 'ngModel',
        link: function (scope, iElement, iAttrs, ngModelCtrl) {
            iElement.on('input', function () {
                ngModelCtrl.$setViewValue(slugger.generateSlug(iElement.val()));
                ngModelCtrl.$render();
            });

            scope.$on('$destroy', function () {
                iElement.off('input');
            });
        }
    }
});

用法:

您应用中的任何地方,

<input ng-model="product.title" slug-input>