2015-04-22 150 views
0

我创建的角的js自定义过滤器,这是我的HTML,自定义过滤器不能正常工作的角度JS

<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> 

这是我的角度js代码

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>) 

如果我使用筛选器:infront的筛选器名称我不能在控制台中得到任何错误,但它仍然无法正常工作。

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

您不应该在控制器内定义过滤器,而是在其外部定义过滤器。 –

+0

我已经这样做,但我仍然在我的控制台中出现错误,如果我使用这个,在我的别名输入字段中value =“@ {{title | filter:replaceSpace}}”我得到没有错误,但代码不起作用即过滤器没有做它的工作是我做错了两个输入字段之间的绑定@Sergiu Paraschiv – xenish

回答

2

你应该控制器外部定义过滤器,而不是使用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:用于从模型中过滤数组,并且当您将另一个过滤器传递给它时,它不执行任何操作

+0

如果我这样做,我得到我的控制台错误,并且两个输入字段之间的绑定不起作用,别名输入字段将有{{title | replaceSpace}}最初在页面加载时。我在控制台中得到的错误是:Error:[$ interpolate:interr] http://errors.angularjs.org/1.3.15/$interpolate/interr?p0=%7B%7B%20title%20...D%7D&p1 = TypeError%3A%20Cannot%20call%20method%20'replace'%20of%20undefined at Error() – xenish

+0

看起来像标题没有被那个时间初始化那么,无论是在控制器'$ scope.title ='' '或者在你的过滤器中检查值是否未定义,然后再替换 – maurycy

+0

谢谢你更新你的答案,这样我就可以接受你的答案了 – xenish

3

你不把过滤器控制器里面,把它放在你的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) { 

}); 
+0

现在,我有相同的代码作为你的,但我仍然在我的控制台中出现错误,如果我使用这个,值=“@ {{title | filter:replaceSpace}}”在我的别名输入字段中我得到没有错误,但代码不起作用,即过滤器没有做它的工作是我做错了两个输入字段之间的绑定@mcpDESIGNS – xenish