0

I think I am polluting my scope but I can't figure out how or how to avoid it:

I have a directive that is called TWICE with different parameters thus:

<div profile-summary attributes="user.attributes" sentiment="positive" limit="3" threshold="20"> </div>
<div profile-summary attributes="user.attributes" sentiment="negative" limit="3" threshold="-20"> </div>

It prints out a top 3 list of scope.attributes sorted asc (if sentiment="positive") or desc (if negative).

This calls a directive thus:

app.directive('profileSummary', function () {
    var features;
    return {
        restrict: "A",
        scope: {
            attributes: '=',
            sentiment: '@',
            threshold: '=',
            limit: '='},
        template: '<h5>{{title}}</h5><ol><li ng-repeat="attr in attributes">{{attr.categorical_value}}</li></ol>',
        link: function (scope, element, attrs) {
            //do stuff to

            if (scope.sentiment == 'positive') {
                scope.title = 'Loves';
                features = _.sortBy(scope.attributes, function (f) {
                    return (100000 - f.reactivity)
                });
                features = _.filter(features, function (f) {
                    return f.reactivity > scope.threshold
                });
            } else {
                scope.title = 'Hates';
                features = _.sortBy(scope.attributes, function (f) {
                    return (f.reactivity)
                });
                features = _.filter(features, function (f) {
                    return f.reactivity < scope.threshold
                });
            }
            features.length = scope.limit;


            scope.attributes = features; //am I polluting global scope? how to avoid?
        }
    }

The problem is that the second directive duplicates the output of the first. If I remove the first directive, I am getting the correct (different) output.

1 Answer 1

1

One way i can think of to fix it would be to use the features array in you directive template instead of attributes array. This way attributes array would not be touched

  template: '<h5>{{title}}</h5><ol><li ng-repeat="attr in features">{{attr.categorical_value}}</li></ol>',

Now features should be defined on the directive scope like this

scope.features = _.sortBy(scope.attributes, function (f) {

So this is not required

scope.attributes = features; //delete

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.