2016-03-21 33 views
0

我正在使用下面这段代码作为指令,而我正在使用此代码ng-model在控制器中返回空值。在控制器中返回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

您是否在视图中定义了“位置”对象? – Grundy

+0

为什么我应该定义位置 – Nodemon

回答

1

您使用tab指令,它具有隔离范围,因此如果您未在所需范围内创建location对象,它将被添加到本地选项卡范围,并且您无法在控制器中访问它。

+0

你的意思是这样** $ scope.location = {}; ** – Nodemon

+0

@Nodemon,是的,像这样。 – Grundy

+0

是啊仍然是相同的错误 – Nodemon

相关问题