是否可以在运行时动态更改指令的引用?
我有一个像这样的输入字段:
<div ng-repeat="header in chartdata.cols">
<input myOwnDirective items-array="current_settings.y_values" ng-value="header.id | num" type="checkbox">
</div>
我在这个输入字段中使用我自己的指令和指令获取对&#34; current_settings.y_values&#34;的引用。值。这只是一个简单的数组。并且上面的代码只创建了5个复选框..
我的指令如下:
app.directive("myOwnDirective", [function () {
return {
restrict: "A",
scope: {
ItemsArray: "=",
value: "@"
},
link: function (scope, elem) {
....
}]);
现在我在我的控制器中有这个值:$ scope.status;这个值可以是例如$ scope.status =&#39; A&#39;或$ scope.status =&#39; B&#39;;
我现在想要从输入字段动态更改值 (项目阵列=&#34; current_settings.y_values&#34) 如果状态是&#39; A&#39;它应该将我的数据存储到current_settings.y_values,如果状态是&#39; B&#39;它应该将值存储在其他地方,例如&#34; current_settings.x_values&#34;
我该怎么做?
编辑:确定Chandermani的解决方案有效,但我现在不会对带有单选按钮和ng-model的输入字段做同样的事情..那里解决方案不起作用或者我做错了什么?输入字段如下所示:
<div ng-repeat="header in chartdata.cols">
<input ng-model="xValues.xValues" type="radio" name="xValues" ng-value="header.id | num">
</div>
在我的控制器中,xValues定义为
$scope.xValues={xValues: null}; // xValues is only one number not an array
如果我改为状态&#39; A&#39;我这样做:
$ scope.xValues.xValues = $ scope.current_settings.x_value;
但这不起作用,该值不存储在$ scope.current_settings.x_value中,我有什么不对?
答案 0 :(得分:0)
您可以在范围上定义新属性,以便在状态更改时引用正确的数组。用它来绑定指令范围。
$scope.$watch('status',function(newValue) {
if(newValue) {
if(newValue=='A') {
$scope.values=$scope.current_settings.y_values
}
else {
$scope.values=$scope.current_settings.x_values
}
}
});
在指令html中使用
<input myOwnDirective items-array="values" ng-value="header.id | num" type="checkbox">