user3230660
user3230660

Reputation:

How do I inject a variable into an angularjs filter

I am trying to create a filter that will concatenate a path with an image name. I store a constant path for images in a value defined on my app like this:

app.value('config', { siteID: '29', apiRoot: 'http://localhost:54003/api', imageRoot: '/Content' });

Now in my filter I want to inject the config object and use it in my filter:

(function () {
var app = angular.module('myApp');
app.filter('imageRoot', ['config', imageRoot]);

function imageRoot(config) {
    return function (imgName,config) {
        return config.imageRoot + '/' + imgName;  // config is undefined
    };
};

})()

Called from html like this:

<img src="{{post.Icon | imageRoot}}" alt="" />

Upvotes: 0

Views: 42

Answers (1)

PSL
PSL

Reputation: 123739

Just remove config argument from filter function, because you already have access to the config in the inner scope and specifying it in the function argument will create a new variable for the innerscope with no value assigned to it.

function imageRoot(config) {
    return function (imgName) { //<-- Remove from here
        return config.imageRoot + '/' + imgName;  
               //^__ This is already accessible from the outer scope
    };
};

Upvotes: 1

Related Questions