Nodemon
Nodemon

Reputation: 1046

Directive returning ng-model value as empty in controller

Am using this below code for directive, while am using this code ng-model returning empty value in controller.

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
    };
});

Under the tab am having two text fields

<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>

if i try to get for $scope.location.city and $scope.location.state value in controller am getting empty value, but if i check {{location.city}} in view am getting value.

before using tab directive form work perfectly, after using tab directive am getting this error.

Upvotes: 0

Views: 391

Answers (1)

Grundy
Grundy

Reputation: 13381

You use tab directive, that have isolate scope, so if you not create location object in needed scope it would be added to local tab scope, and you can't access it in your controller.

Upvotes: 1

Related Questions