簡體   English   中英

如何避免在angular.js指令中污染模型的范圍

[英]How to avoid polluting scope in angular.js directive that modifies model

我認為我正在污染范圍,但無法弄清楚如何或如何避免它:

我有一個名為TWICE的指令,具有不同的參數,因此:

<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>

它打印出scope.attributes的前3個列表。按升序(如果scope.attributes =“ positive”)或降序(如果是負數)排序的scope.attributes

這樣調用指令:

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?
        }
    }

問題在於第二個指令重復了第一個指令的輸出。 如果刪除第一個指令,則得到正確的(不同的)輸出。

我可以解決的一種方法是在指令模板中使用features數組而不是attribute數組。 這樣屬性數組將不會被觸及

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

現在應該在指令范圍內定義功能,如下所示

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

因此這不是必需的

scope.attributes = features; //delete

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM