2016-04-29 8 views
2

私はmy-attributeという属性に基づいて画面にグラフを描画する指示文myp-my-directiveを作成するAngularJSアプリケーションを持っています。これが私のやり方です。それは動作します:

HTML

<myp-my-directive my-attribute="[1, 2, 3]"> 
</myp-my-directive> 

角度指令:

myapp.directive('mypMyDirective',function() { 
    return { 
     restrict:'E', 
     scope: { 
     myAttribute: '=' 
     }, 
     controller: 'StuffCtrl', 
     controllerAs: 'stuffCtrl', 
     bindToController: true, 
     templateUrl: 'myHtml.html' 
    }; 
    } 
); 

角度コントローラー:

myapp.controller('StuffCtrl', function($scope) { 
    var self = this; 

    $scope.$watch(function() {return self.myAttribute;}, function (objVal) 
     { 
     if (!(typeof objVal === "object" && objVal.length > 0)) { 

      var myObject = Object.assign({}, objVal.data); 
      // Draw a fancy chart based using d3.js based on myObject 
     } 
     } 
    ); 
    } 
); 

上記作品。

しかし、私はただ1つではなく、2つの属性に基づいてグラフを描画する必要があることに気付きました。私はこれを行うには$scope.$watchの代わりに最後の引数true 。今のところ(暫定的なステップとして)、コントローラがある値を含む配列を取って、それが機能するかどうかを確認しました。私のコントローラは次のようになります。

myapp.controller('StuffCtrl', function($scope) { 
    var self = this; 

    $scope.$watch(function() {return [self.myAttribute];}, function (objVal) 
     { 
     if (!(typeof objVal[0] === "object" && objVal[0].length > 0)) { 

      var myObject = Object.assign({}, objVal[0].data); 
      // Draw a fancy chart based using d3.js based on myObject 
     } 
     } 
    ); 
    }, true 
); 

しかし、これは次のエラー生成:

angular.js:13236 RangeError: Maximum call stack size exceeded 
    at equals (angular.js:1048) 
    at equals (angular.js:1058) 
    at equals (angular.js:1074) 
    at equals (angular.js:1058) 
    at equals (angular.js:1074) 
    at equals (angular.js:1058) 
    at equals (angular.js:1074) 
    at equals (angular.js:1058) 
    at equals (angular.js:1074) 
    at equals (angular.js:1058) 

はなぜ?私のコントローラの2つのバージョンが同等であるべきではありませんか?なぜ1人は働いていますが、もう1人は失敗していますか?指令の第2の属性をコントローラに送る最良の方法は何ですか?

答えて

3

アレイの場合、$scope.$watchCollection()を使用する必要があります。 here

を読んで、この

$scope.$watchCollection(function() {return [self.myAttribute];}, function (newVal, oldVal) 
    { 
    if (!(typeof newVal[0] === "object" && newVal[0].length > 0)) { 

     var myObject = Object.assign({}, newVal[0].data); 
     // Draw a fancy chart based using d3.js based on myObject 
    } 
    } 
); 
+0

YESを試してみてください!ありがとうございました –

関連する問題