javascript - 单选按钮中的 ng-model 始终未定义

标签 javascript angularjs

当我触发 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>

这是 Controller :

$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 指令确实创建了一个子作用域,该子作用域原型(prototype)是从父作用域继承的。

On contrast Prototypal Inheritance means?

If you have scope hierarchy, then parent scope property are accessible inside child scope, only if those property are object (originally object referenced is passed to child scope without creating its new reference). But primitive datatypes are not accessible inside child scope and if you looked at your code addCustom scope variable is of primitive dataType.

问题是 dir 变量与您在 ng-if 中使用的 radio ng-model 是原始数据类型。因此,当 ng-if 渲染 div 时,它确实会在那里创建一个子作用域,该作用域再次具有 dir 值。因此 Controller dir 变量与 ng-if 的单选按钮 dir 范围变量不同。

为了解决问题,您需要更改

data-ng-model="dir"

data-ng-model="post.dir"

这样就可以使用DOT规则来遵循原型(prototype)继承规则。

并且从 post 对象中,您只能获取 post.dir 按钮的值,然后无需向其传递 dir 的显式值。我不会解释幕后到底发生了什么,你可以引用 this similar answer这里有其他方法来完成这件事。

关于javascript - 单选按钮中的 ng-model 始终未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35520711/

相关文章:

javascript - jQuery用一个元素替换多个元素

java - jqgrid如何显示服务器端消息

javascript - Angular JS 密码强度显示出现问题

java - 使用 Java 的 Angular 应用程序

angularjs - 使用 angularjs 显示加载图标或加载进度条

javascript - 使导航菜单响应

javascript - React 16.7有State Hook,我可以在任何情况下使用功能组件而不是类组件吗?

javascript - 禁用 ng-autocomplete (或一般禁用 div 属性)

javascript - 如何从 Angular.js 中的 index.html 页面调用指令中的函数

mysql - 使用 AngularJS 和 Spring Security 进行身份验证