0

My question is that how to call 1 controller $scope to another controller in Angular JS. Bascially The structure is that, I have two controller one is AddController and the other one is ViewController. Basically I want the form with fields of AddController in ViewController. $rootScope.name = data.name, email and phone is not showing the data on the form fields once I click on Edit.

What I've already tried.

In HTML

<div ng-app="app">
  <div ng-controller="AddController">
    <legend>Add Students</legend>
    <form class="well">
      <label>Name</label>
      <input type="text" name="name" ng-model="name" />
      <label>Email</label>
      <input type="text" name="email" ng-model="email" />
      <label>Phone</label>
      <input type="text" name="phone" ng-model="phone" />
      <br/>

      <div ng-if="isUpdate">
        <input type="hidden" name="id" ng-model="id" />
      </div>

      <div ng-show="addData">
        <input type="button" value="Save" ng-click="saveStudent()" class="btn btn-primary" />
      </div>
      <div ng-show="!addData">
        <input type="button" value="Update" ng-click="updateStudent()" class="btn btn-primary" />
      </div>
    </form>
  </div>
  <div ng-controller="ViewController">
    <legend>View Students</legend>
    <table class="table table-striped table-bordered">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Email</th>
          <th>Phone</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="student in students">
          <td>{{ $index; }}</td>
          <td>{{ student.name }}</td>
          <td>{{ student.email }}</td>
          <td>{{ student.phone }}</td>
          <td><a href="javascript:void(0)" ng-click="edit($index)">Edit</a> | <a href="javascript:void(0)" ng-click="delete($index)">Delete</a></td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

In JS

var app = angular.module('app', []);

app.service('StudentsData', function($rootScope){
    var s;
    var students = [
        {name: 'Tariq Ali', email: '[email protected]', phone: '58757'},
        {name: 'Faizan Ali', email: '[email protected]', phone: '24545'}
    ];

    this.list = function(){
        return students;
    }

    this.single = function(id){
        for(s=0; s<=students.length; s++){
            if(s == id){
                return students[s];
            }
        }
    }

    this.insert = function(data){
        students.push(data);
    }

    this.update = function(updatedData, id){
        for(s=0; s<=students.length; s++){
            if(s == id){
                students[s] = updatedData;
            }
        }
    }

    this.delete = function(id){
        students.splice(id, 1);
    }

    this.name = function(){

    }


});

app.controller('AddController', function($scope, StudentsData, $rootScope){

    $scope.$broadcast('someEvent', [1,2,3]);

    $rootScope.addData = true;
    $scope.saveStudent = function(){
        StudentsData.insert({name: $scope.name, email: $scope.email, phone: $scope.phone});

        $scope.name = '';
        $scope.email = '';
        $scope.phone = '';
    }

    $scope.updateStudent = function(){
        var updatedData = {name: $scope.name, email: $scope.email, phone: $scope.phone};
        StudentsData.update(updatedData, $scope.id);

        /*$scope.name = '';
        $scope.email = '';
        $scope.phone = '';
        $rootScope.addData = true;*/
    }


});

app.controller('ViewController', function($scope, StudentsData, $rootScope){

    $scope.$on('someEvent', function(event, mass) {console.log(mass)});

    $scope.students = StudentsData.list();

    $scope.delete = function(id){
        StudentsData.delete(id);
    }

    $scope.edit = function(id){
        var data = StudentsData.single(id);

        $rootScope.name = data.name;
        $rootScope.email = data.email;
        $rootScope.phone = data.phone;
        $rootScope.addData = false;
        $rootScope.isUpdate = true;
        $rootScope.id = id;
        //console.log($rootScope.addData);

        //StudentsData.update(id);
    }
});

Here is my fiddler http://jsfiddle.net/npm5u5h0/ For first time if you click on edit its working fine but if you add a new student and after edit the newly created student the textfields are not showing the data.

7
  • why don't you put them in one controller? Commented Sep 16, 2014 at 15:12
  • why are you using $rootScope for the fields in ViewCtrl and not $scope? Commented Sep 16, 2014 at 15:16
  • @charlietfl because $rootScope is sometimes working as I want. but $scope isn't working even in a single time Commented Sep 17, 2014 at 8:08
  • somethings wrong then. Shouldn't have to do it that way. Likely the fact that you aren't using objects rather primitives Commented Sep 17, 2014 at 12:55
  • @charlietfl, you can check the fiddle jsfiddle.net/npm5u5h0 For first time if you click on edit its working fine but if you add a new student and after edit the newly created student the textfields are not showing the data. Commented Sep 18, 2014 at 7:42

2 Answers 2

1

Why not have two controllers that both call the same service? They you could put the information in the service and have them both reference that.

angular.module('mycontrollers').controller('controllername', ['myService', function (myService) {
    $scope.email = myService.getEmail;
}]);

angular.module('mycontrollers').controller('controllername2', ['myService', function (myService) {
    $scope.email = myService.getEmail;
}]);

angular.module('myservices').service('myService', ['$rootScope', function ($rootScope) {
    var self = this;
    self.getEmail = function () {
       ...
       return $rootScope.email;
    };
    self.setEmail = function (email) {
        $rootScope.email = email;
    };
}]);
Sign up to request clarification or add additional context in comments.

1 Comment

not working. here is my fiddler jsfiddle.net/npm5u5h0 For first time if you click on edit its working fine but if you add a new student and after edit the newly created student the textfields are not showing the data.
0

You could name the addContoller div with an ID such as "addController"

Then from within your viewController, you could grab the other scope with

var myEl = angular.element(document.querySelector('#addController')); var myScope = angular.element(myEl).scope();

and then $scope.name = myScope.name

5 Comments

Note: There is certainly a cleaner way to do this with injection, but I am answering the question directly.
The Controller should never have any code that deals with the DOM, regardless if its querying DOM elements or manipulating them. Tom's answer is the way to go with the problem, as for your solution it sways away against AngularJS principles.
Fair enough. But that wasn't the question. "Basically I want the form with fields of AddController in ViewController."
You might want to read the Developer's Guide, make sure to read the "Do not use controllers to" list. Specifically, the first and fourth item on the list.
Here is my fiddler jsfiddle.net/npm5u5h0 For first time if you click on edit its working fine but if you add a new student and after edit the newly created student the textfields are not showing the data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.