我試圖解決一個謎題,爲什麼ng-model的輸入[radio]控件沒有像我期望的那樣設置。 加載頁面後,所有的收音機都會正確啓動。點擊不同的控件改變radioVal變量 - 它的值在頁面中呈現。輸入廣播ng-model畢竟沒有更新
問題是,它看起來只發生在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'])
感謝charlietfl,你的推理使感官和作品。 但是來自外部控制器mainCtrl的$ scope.showModal也是一個原語,雙向綁定在這裏仍然有效(參見:scope.hideModal = function(){scope.show = false; ...在指令中。我仍然不明白 – gvlax
正確,但是正在傳遞給聲明與您的隔離範圍的雙向綁定的模態指令。內角是看你的。案件是不同的.. ng-model也是一個指令。在這裏可以看到所有帖子中的「use dot」。 – charlietfl
是的。我認爲「ng-model也是一個指令」是我錯過了解我的問題。我不會感到驚訝的是,如果我無法找到的右側radioVal(顯示在頁面中的值與其值相同)由其[NgModelController]管理(https://docs.angularjs.org/api/ng/type/ ngModel.NgModelController)不是我的控制器。 – gvlax