我使用下面的代码用于指令,同时使用此代码ng-model在控制器中返回空值。
myApp.directive('tabs', function() {
return {
restrict: 'E',
transclude: true,
scope: {},
controller: [ "$scope", function($scope) {
var panes = $scope.panes = [];
$scope.select = function(pane) {
angular.forEach(panes, function(pane) {
pane.selected = false;
});
pane.selected = true;
};
this.addPane = function(pane) {
if (panes.length === 0) $scope.select(pane);
panes.push(pane);
};
}],
template:
'<div class="tabbable">' +
'<ul class="nav nav-tabs">' +
'<li ng-repeat="pane in panes" ng-class="{active:pane.selected}">'+
'<a href="" ng-click="select(pane)">{{pane.title}}</a>' +
'</li>' +
'</ul>' +
'<div class="tab-content" ng-transclude></div>' +
'</div>',
replace: true
};
}).
directive('pane', function() {
return {
require: '^tabs',
restrict: 'E',
transclude: true,
scope: { title: '@' },
link: function(scope, element, attrs, tabsCtrl) {
tabsCtrl.addPane(scope);
},
template:
'<div class="tab-pane" ng-class="{active: selected}" ng-transclude>' +
'</div>',
replace: true
};
});
在标签下有两个文本字段
<form role="form">
<legend>Add City</legend>
<div class="form-group">
<label for="">State</label>
<input type="text" ng-model="location.state" id="input" class="form-control" placeholder="Enter state name">
</div>
<div class="form-group">
<label for="">City</label>
<input type="text" ng-model="location.city" id="input" class="form-control" placeholder="Enter city name">
</div>
<button type="button" class="btn btn-success">Create</button>
<button type="button" ng-click="UpdateCity()" class="btn btn-warning">Update</button>
</form>
如果我尝试获取控制器中的$scope.location.city
和$scope.location.state
值,则会获得空值,但如果我检查{{location.city}}
,则会获得值。
在使用tab指令表单之前完美地工作,使用tab指令后得到此错误。
答案 0 :(得分:1)
您使用具有隔离范围的tab指令,因此如果您不在需要的范围内创建location
对象,它将被添加到本地选项卡范围,您无法在控制器中访问它。