2015-06-28 41 views
0

我使用這個插件數據:COUNTUPAngularJS指令Countup.JS得到模型

,我有以下指令:

directive('upCounter', function() { 

    return { 
     restrict: 'EAC', 
     link: function (scope, el, attrs) { 
      var $el = angular.element(el), 
       sm = scrollMonitor.create(el); 

      sm.fullyEnterViewport(function() { 
       var opts = { 
        useEasing: attrDefault($el, 'easing', true), 
        useGrouping: attrDefault($el, 'grouping', true), 
        separator: attrDefault($el, 'separator', ','), 
        decimal: attrDefault($el, 'decimal', '.'), 
        prefix: attrDefault($el, 'prefix', ''), 
        suffix: attrDefault($el, 'suffix', '') 
       }, 
       $count = attrDefault($el, 'count', 'this') == 'this' ? $el : $el.find($el.data('count')), 
       from = attrDefault($el, 'from', 0), 
       to = attrDefault($el, 'ng-model', 100), 
       duration = attrDefault($el, 'duration', 2.5), 
       delay = attrDefault($el, 'delay', 0), 
       decimals = new String(to).match(/\.([0-9]+)/) ? new String(to).match(/\.([0-9]+)$/)[1].length : 0, 
       counter = new countUp($count.get(0), from, to, decimals, duration, opts); 

       setTimeout(function() { counter.start(); }, delay * 1000); 

       sm.destroy(); 
      }); 
     } 
    }; 
}). 

我怎樣才能改變指令,這樣我可以通過一個data-ng-modelto參數的值?

編輯:

我已經嘗試添加scope:{ ngModel: '='}但我得到這個錯誤:

錯誤:$編譯:multidir 多個指令資源爭

多個指令[upCounterupCounter,新/隔離範圍]詢問{4}:{5}

說明

將多個指令應用於相同的DOM元素時會發生此錯誤,並且處理它們將導致衝突或不支持的配置。

要解決此問題,請刪除導致衝突的其中一個指令。

應用到相同的元件的多個不兼容的指令的實施例方案包括:

  • 多重指令請求分離範圍。
  • 以相同名稱發佈控制器的多條指令。
  • 使用transclusion選項聲明的多個指令。
  • 多個指令試圖定義一個模板或templateURL。
+0

你可以用'要求:「ngModel''然後在鏈接功能通過ngModel作爲第四個參數。這將允許您在鏈接功能中訪問ngModel API。 ngModel。$ viewValue使您可以訪問當前值。如果你需要的話,會嘗試模擬一個示例演示。 – jme11

+0

感謝您的信息。我實際上已經像你所提到的那樣嘗試過了,但在指令中'ngModel。$ viewValue'的值是'Nan' – user2818430

回答

0

我剛纔發現您可能沒有使用$ watch等待第一個摘要後初始化的值。如果你看一下ngModel指令源,你會看到ngModelController將$ viewValue初始化爲NaN。

因此,增加了$表就可以了:

var app = angular.module('countup.demo', []); 
 
app.controller('CounterCtrl', ['$scope', function($scope){ 
 
    $scope.countervalue = 100; 
 
}]) 
 
.directive('upCounter', function() { 
 

 
    return { 
 
    restrict: 'A', 
 
    require: 'ngModel', 
 
    link: function (scope, element, attrs, ngModel) { 
 
     scope.$watch(ngModel, function(newval) { 
 
     alert(ngModel.$viewValue); 
 
     }); 
 
     
 
    } 
 
    }; 
 
});
<script src="https://code.angularjs.org/1.3.16/angular.js"></script> 
 

 
<div ng-app="countup.demo"> 
 
    <div ng-controller="CounterCtrl"> 
 
    <div up-counter id="counter" ng-model="countervalue"></div> 
 
    <p>countervalue: {{countervalue}}</p> 
 
    </div> 
 
</div>