[英]Angular Nested Directive Data Binding
我在項目中使用angular-nvd3 。 它公開了一個元素指令,如下所示:
<div nvd3 options="" data=""></div>
這將根據選項和數據值呈現圖表。 它為options
和data
屬性提供兩種方式的數據綁定。 更改數據或選項時,圖表將更新。
我一直在嘗試將此指令包裝在我自己的指令中,以通過其他接口公開較少的功能(以下為https://www.airpair.com/angularjs/posts/component-based-angularjs-directives )
ngModule.directive('myDirective', [function() {
template: '<div nvd3 options="ctrl.options" data="ctrl.data"></div>',
scope: {},
bindToController: {
w: '=',
h: '='
},
controllerAs: 'ctrl',
controller: ['$scope', function($scope) {
var ctrl = this;
$scope.$watch(function() { return ctrl.w; }, render );
$scope.$watch(function() { return ctrl.h; }, render );
function render() {
ctrl.data = ctrl.data || {} # omitted object definition
ctrl.options = ctrl.options || {} # omitted object definition
ctrl.options.chart.width = ctrl.w;
ctrl.options.chart.height = ctrl.h;
}
}]
}]);
這對於初始渲染工作正常。 但是,在測試時,修改w
或h
參數似乎無法使圖表更新。
describe('my-directive', function() {
var scope, element, render;
function getSvgAttr(el, attr) {
return el.find('svg')[0].getAttribute(attr);
}
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
var compileFn = $compile(
'<div my-directive w="w" h="h">'
);
render = function() {
element = compileFn(scope);
$rootScope.$digest();
}
}));
it('should resize', function() {
scope.w = 400;
scope.h = 200;
render();
var ctrl = element.isolateScope().ctrl();
expect(ctrl.w).toBe(400);
expect(ctrl.h).toBe(200);
expect(getSvgAttr(element, 'width')).toBe('400');
expect(getSvgAttr(element, 'height')).toBe('200');
scope.w = 200;
scope.h = 400;
scope.$digest();
expect(ctrl.w).toBe(200);
expect(ctrl.h).toBe(400);
expect(ctrl.w).toBe(200);
expect(ctrl.h).toBe(400);
expect(getSvgAttr(element, 'width')).toBe('200');
expect(getSvgAttr(element, 'height')).toBe('400');
});
});
最后兩個斷言失敗。 angular-nvd3
,修改選項和數據會修改圖形。
但是,當我添加一個包裝器指令時,范圍似乎發生了變化,但圖形卻沒有變化。
任何幫助將不勝感激! 我的印象是,使用bindToController
我也不需要任何$scope.$watch
行。
似乎在上面的控制器中,您重復了以下代碼行:
$scope.$watch(function() { return ctrl.w; }, render );
我假設您打算將第二次迭代更改為以下內容:
$scope.$watch(function() { return ctrl.h; }, render );
結果,該程序在雙重監視“ w”參數時跳閘,而沒有監視“ h”參數的更改。
但是,這可能只是問題的一部分。
希望能幫助到你,
C§
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.