自定义过滤器不工作 angular js

Custom filter not working angular js

我正在 angular js 创建一个自定义过滤器,这是我的 html,

<div class="box-body">

<div class="form-group">
    <label>Page-Title:</label>
    <input type="text" required value="" data-ng-model="title" name="page_title" class="form-control" id="" placeholder="Enter Page Title">                     
</div>

<div class="form-group">
    <label>Page-Alias:</label>
    <input type="text" value="@{{ title | replaceSpace}}" name="page_alias" class="form-control" id="" placeholder="Auto-Generated If Left Blank">
</div>

这是我的angularjs代码

var app = angular.module('CustomAngular', []);
app.controller('CustomCtrl', function ($scope) {
    app.filter('replaceSpace', function () {
        return function (input) {
            return input.replace(/ /g, '-').toLowerCase();
        };
    });
});

过滤器不工作,而且我在控制台中收到错误消息。

Error: [$injector:unpr] http://errors.angularjs.org/1.3.15/$injector/unpr?p0=slugifyFilterProvider%20%3C-%20slugifyFilter
    at Error (<anonymous>)

如果我在过滤器名称前使用 filter: 我在控制台中没有收到任何错误,但它仍然无法正常工作。

<input type="text" value="@{{ title | filter:replaceSpace }}" name="page_alias" class="form-control" id="" placeholder="Auto-Generated If Left Blank">

您不要将过滤器放在控制器内,而是将其放在 var app 行之后。它是一个独立的东西,就像控制器/指令/等等。

var app = angular.module('CustomAngular', []);

// Here's where it goes
// Also now any/all controllers can use it!

app.filter('replaceSpace', function () {
    return function (input) {
        return input.replace(/ /g, '-').toLowerCase();
    };
});

app.controller('CustomCtrl', function ($scope) {

});

您应该在控制器之外定义过滤器而不是使用 filter: 因为它有不同的含义,这是使用过滤器的正确方法

<input type="text" value="@{{ title | replaceSpace }}" name="page_alias" class="form-control" id="" placeholder="Auto-Generated If Left Blank">

虽然你应该通过 $scope.title = '' 初始化模型或者在你的过滤器中检查 运行 replace 只有当输入被定义时,否则你会得到 JS 错误

filter: 用于从模型中过滤数组,当您将另一个过滤器传递给它时,它什么都不做