I want to declare my own directive in AngularJS which takes as an attribute a string source of a file it must load and then modify in some way and display.
I have an AngularJS directive and filter defined as follows -
app.directive("customTag", function ($compile) {
return {
restrict: 'E',
require: 'src',
scope: {
value: "=src"
},
template: '<div ng-bind-html-unsafe="value | myFilter"></div>',
replace: true
};
});
app.filter('myFilter', function () {
return function (value) {
$http({
url: value,
method: 'GET'
}).success(function (data, status, headers, config) {
value = data; // gets a string value
}).error(function (data, status, headers, config) {
value = "Error getting content";
});
return ModifyString(value);
};
});
And the corresponding HTML is -
<customTag src="/test.txt"></customTag>
However, this gives me an error saying that the $http is not defined in the scope. How do I fix this?
Furthermore, I think that I will run into the problem that $http call will be an asynchronous one, so the filter will not return the correct value after the file has been read.
You need to inject $http provider in your filter provider:
app.filter('myFilter', function ($http) {...
That aside, you should reconsider your logic. Filters are not supposed to deal with server and promises. That's what services and directives are for.