2
我有一個AngularJS應用程序,我在其中創建了一個指令myp-my-directive
,該指令根據屬性my-attribute
在屏幕上繪製圖表。這就是我的做法。它的工作原理:
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.我知道我可以返回數組$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)
爲什麼?我的控制器的兩個版本不應該相同嗎?爲什麼一個人工作,但另一個失敗?從指令中向控制器發送第二個屬性的最佳方法是什麼?
YES!謝謝 –