我试图解决一个难题,为什么输入 [radio] 控件的 ng-model 没有按我预期的那样设置。 加载页面后,所有 radio 都会正确启动。单击不同的控件会更改 radioVal 变量 - 它的值呈现在页面中。
问题是它看起来只发生在 DOM 中。当我调试代码时,$scope.radioVal
总是一样的……
modalDialog
的隔离范围不包含 radioVal
属性。
radio ng-model
是在哪个范围内创建的?它是它的不同实例吗?
可以找到工作代码here on jsfiddle .
我的 html 代码是:
<div ng-app = "app">
<div ng-controller="mainCtrl">
<a ng-click="showModalDlg()">Click me</a>
<br/><br/>
<modal-dialog show="showModal" action="actionFun">
<form>
<input type="radio" ng-model="radioVal" value="1">One<br/>
<input type="radio" ng-model="radioVal" value="nothing changes me">Two<br/>
<input type="radio" ng-model="radioVal" value="3">Three<br/>
<br/><br/>
The model changes in the DOM as expected: <b>radioVal = {{radioVal | json}}</b>
<br/>
but by pressing the Action button you can see that the model has not been modified.
</form>
<a class="button" action>Action</a>
</modal-dialog>
</div>
</div>
我的 Angular 代码:
angular.module('common', [])
.controller('mainCtrl', ['$scope', function($scope){
$scope.showModal = false;
$scope.radioVal = "nothing changes me";
$scope.showModalDlg = function() {
$scope.showModal = !$scope.showModal;
};
$scope.actionFun = function() {
console.log('actionFun ...' + $scope.radioVal);
};
}]).directive('modalDialog',
function () {
return {
restrict: 'E',
scope: {
show: '=',
action: '&',
},
replace: true,
transclude: true,
link: function (scope, element, attrs) {
scope.hideModal = function () {
scope.show = false;
scope.$apply();
};
$('a[hide]', element).on('click', function(){
scope.hideModal();
});
$('a[action]', element).on('click', function(){
console.log('There is no radioVal in isolated scope either ... ' + scope.radioVal);
scope.action()();
scope.hideModal();
});
},
template: '<div class=\'ng-modal\' ng-show=\'show\'><div class=\'ng-modal-overlay\'></div><div class=\'ng-modal-dialog\' ng-style=\'dialogStyle\'><div class=\'ng-modal-dialog-content\' ng-transclude></div></div></div>'
}
});
angular.module('app', ['common'])
最佳答案
始终在 ng-model
中放置一个点
您目前正在尝试将原语传递给嵌套范围,这将破坏双向绑定(bind)。但是,如果您传递一个对象,它将保持对原始对象的引用
简单地改变:
$scope.radioVal = "nothing changes me";
收件人:
$scope.myModel={radioVal : "nothing changes me"};
并在 ng-model
中使用点
<input ng-model="myModel.radioVal">
更改继承,因此更改绑定(bind)。
关于javascript - 输入 radio ng-model 毕竟没有更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24783589/