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