javascript - How to avoid polluting scope in angular.js directive that modifies model -
i think polluting scope can't figure out how or how avoid it:
i have directive called twice 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 top 3 list of scope.attributes sorted asc (if sentiment="positive") or desc (if negative).
this calls 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 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 polluting global scope? how avoid? } } the problem second directive duplicates output of first. if remove first directive, getting correct (different) output.
one way can think of fix use features array in directive template instead of attributes array. way attributes array not touched
template: '<h5>{{title}}</h5><ol><li ng-repeat="attr in features">{{attr.categorical_value}}</li></ol>', now features should defined on directive scope this
scope.features = _.sortby(scope.attributes, function (f) {
so not required
scope.attributes = features; //delete
Comments
Post a Comment