我有弹出气泡的指令,其中弹出窗口中显示的按钮在属性中作为对象数组提供:
JS(控制器)
$scope.buttons = [{ label: 'OK' }, { label: 'Cancel' }]
该指令如下所示:
HTML
<ui-popup buttons="buttons"></ui-popup>
JS(指令)
'use strict';
angular
.module('ui')
.directive('uiPopup', [function () {
return {
replace: true,
restrict: 'E',
transclude: true,
templateUrl: '/uikit/views/ui-popup.html',
scope: {
buttons: '=',
anchor: '@',
x: '@',
y: '@'
},
link: function ($scope, element, attrs, ngModel) {
...
}
};
}]);
这很好用。但是,我需要的是从气泡中没有按钮开始,然后在应用程序中发生事件时添加按钮。所以我从一个空数组开始,并使用$scope.buttons.push(obj)
添加每个按钮。注意我维护原始数组,而不是替换数组,因此数据绑定不应该被破坏。但是,新按钮不会显示在气泡中,调试显示按钮未添加到指令范围内。
经过实验,我偶然发现如果我从非空数组开始然后添加它就可以了。为什么角度数据绑定会破坏空数组?我该怎么做才能解决这个问题?
修改
该事件在ng-click
上调用,如下所示:
JS(控制器)
$scope.onClick = function () {
$scope.locked = true;
$scope.buttons.push({ label: 'OK' });
};
答案 0 :(得分:1)
指令HTML如下所示:
...
<div class="buttons" ng-if="buttons">
<ui-button color="primary" size="small" ng-repeat="button in buttons">{{ button.label }}</ui-button>
</div>
...
如果buttons
真实,您可以看到弹出窗口中的按钮。有趣的是,div.buttons
在buttons
为空时未显示,即使!![]
在javascript中为true,所以我只能假设Angular使用自己的相等函数来测试。但是,即使随后将一个按钮添加到数组中,div也没有显示。
当我将等式更改为ng-if="buttons.length"
时,(因为它可能应该从一开始就是这样),所以事情正常。