我试图解决一个难题,为什么没有像我期望的那样设置输入[无线电]控件的ng模型。 加载页面时,所有无线电都会正确启动。单击不同的控件会更改radioVal变量 - 其值将在页面中呈现。
问题是它看起来只发生在DOM中。当我调试代码时,$scope.radioVal
始终是相同的......
孤立的modalDialog
范围不包含radioVal
属性。
在哪个范围内创建了广播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.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'])
答案 0 :(得分:5)
总是在 ng-model
您目前正在尝试将基元传递给嵌套范围,这将破坏双向绑定。如果传递一个对象,它将保持对原始对象的引用
简单地改变:
$scope.radioVal = "nothing changes me";
要:
$scope.myModel={radioVal : "nothing changes me"};
使用ng-model
<input ng-model="myModel.radioVal">
更改继承,从而更改绑定。
的 DEMO 强>
答案 1 :(得分:0)
在指令中声明scope
对象时,意味着您为该指令的每个实例创建一个隔离范围。您需要将radioVal
传递给使用该指令创建的隔离(子)范围。
HTML:
<modal-dialog show="showModal" action="actionFun" value="radioVal">
JS:
scope: {
show: '=',
action: '&',
radioVal: '='
},