Zichen Ma Zichen Ma - 4 months ago 17
AngularJS Question

AngularJS filter does not sync the input value from module

Hello I am new to AngularJS and met a question. I need to create a customized filter to filter a string, however the filter cannot sync the input result. Because the filter.js has to be made into a separated JS file, I thought I have to import $scope.delimiter from controller.js to filter.js, but I don't know how to do it. Thank you very much in advanced.
HTML:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Tokenizer Filter</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="controller.js"></script>
<script src="filter.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="TokenizeControler">
<p>Input: <input ng-model="greeting" /></p>
<p>Delimiter: <input id="delimiter" ng-model="delimiter" /></p>
<p>{{delimiter}}</p>
<p>{{greeting | tokenize: defualt}}</p>
<p>{{greeting | tokenize}}</p>
</div>
</body>
</html>


Controller.js:

var myApp = angular
.module("myApp", [])
.controller("TokenizeControler",
function ($scope) {
$scope.greeting = "Angular is awesome";
$scope.delimiter = "#";
$scope.defualt = true;

});


filter.js:

myApp.filter("tokenize", function () {
return function (content, defualt) {
if (angular.isString(content)) {
var noSpace, output;
noSpace = content.replace(/ +/g, "");
if (defualt) {
return output = noSpace.split('').join(',') + " (Default)";
} else {
delimiter = document.getElementById('delimiter').value;

return output = noSpace.split('').join(delimiter) + "(With option)";
}
} else {
return content;
}
};
});

Answer

See this plunker : https://plnkr.co/edit/kXQGTj1sABKOuxObOhn7?p=preview.

Default isn't needed, just check if delimiter is present

filter("tokenize", function () {
return function (content, delimiter) {
        if (angular.isString(content)) {
            return content
                      .replace(/ +/g, "")
                      .split('')
                      .join(delimiter || ',');
        } else {
            return content;
        }
    };
})

And the use

<p>{{delimiter}}</p>
<p>{{greeting | tokenize}}</p>
<p>{{greeting | tokenize:delimiter}}</p>
Comments