单选按钮中的 ng 模型始终未定义

ng-model from radio button is always undifined

本文关键字:未定义 模型 ng 单选按钮      更新时间:2023-09-26

当我触发ng-click事件时,ng-model总是未定义的。我想获取所选值。别名效果很好。

<div ng-if="post.direction != 'digital_in' && post.direction != 'digital_out'">
    <label><input data-ng-model="dir" type="radio" name="direction" value="digital_in">digital input</label>
    <label><input data-ng-model="dir" type="radio" name="direction" value="digital_out">digital output</label>
    {{dir}}
 </div>
<td><button type="submit" class="btn btn-warning" ng-click="updatePin(post, alias, direction.value())"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span></button></td>

这是控制器:

$scope.updatePin = function(post, alias, dir){
    console.log(post.id);
    post.alias = "" + alias;
    post.direction = "" + dir;
    $http.post('http://localhost:9000/activePinsUpdate?id=' + post.id , post).success(function(data, status) {
        $scope.loadData();
    });
};

ng-if指令确实创建了一个子作用域,该子作用域通常继承自父作用域。

对比 原型遗传意味着?

如果有作用域

层次结构,则可以访问父作用域属性 在子作用域内,仅当这些属性是对象(最初是 引用的对象被传递到子作用域而不创建其新的 参考资料)。但是基元数据在子级内部无法访问 范围,如果您查看了代码 addCustom 范围变量是 基元数据类型。

问题是您在内部使用的无线电ng-model dir变量ng-if是原始数据类型。因此,当ng-if呈现div时,它确实会在那里创建一个子范围,该子范围再次具有dir值。所以控制器dir变量不同于ng-if的单选按钮dir作用域变量。

为了解决问题,您需要从

data-ng-model="dir"

data-ng-model="post.dir"

因此,将使用DOT rule遵循原型继承规则。

并且只有从 post 对象中您可以获取post.dir按钮的值,无需将其显式传递 dir 值。我不打算解释幕后到底发生了什么,因为你可以在这里参考这个类似的答案,它有其他方法来完成这件事。

使用带有ng-model的ngValue作为对象属性

喜欢这个

<div ng-if="post.direction != 'digital_in' && post.direction != 'digital_out'">
    <label><input data-ng-model="post.dir" type="radio" name="direction" ng-value="digital_in">digital input</label>
    <label><input data-ng-model="post.dir" type="radio" name="direction" ng-value="digital_out">digital output</label>
    {{dir}}
 </div>

您可以像这样在 Ctrl 中访问它

post.alias = "" + alias;
post.direction = "" + post.dir;

您可能需要在小提琴中共享您的代码,这是获得帮助的好方法。

建议 :- 您可能需要使用预角度绑定 UI - 角度用户界面 http://angular-ui.github.io/bootstrap/versioned-docs/0.12.0/#/getting_started 如果您是初学者,请尝试从上述链接开始,因为这些 已经绑定了 angularjs。所以你不会面对上面的那种 问题。

您正在使用纯 html 与 angular 绑定,这会造成混乱。终于理解了角度 UI。

溶液:-缺少的东西是 ng 值 .

<div ng-if="post.direction != 'digital_in' && post.direction != 'digital_out'">
    <label><input data-ng-model="dir" type="radio" name="direction" ng-value="digital_in" ng-checked='true'>digital input</label>
    <label><input data-ng-model="dir" type="radio" name="direction" ng-value="digital_out">digital output</label>
    {{dir}}
 </div>

如果仍然不起作用

预定义$scope.dir='digital_in'; // it updates on selecting radio.

$scope.updatePin = function(post, alias, dir){
    console.log(post.id);
    post.alias = "" + alias;
    post.direction = "" + $scope.dir;   //value Updates on Check 
    $http.post('http://localhost:9000/activePinsUpdate?id=' + post.id , post).success(function(data, status) {
        $scope.loadData();
    });
};

祝你好运!!