0
 <div data-ng-app="myApp" data-ng-controller="ProjectHighLigthsController">
    <div ng-form="userForm">
        <img alt="" data-ng-click="addAnswers($event)" data-ng-show="isAdmin" src="/SaveBttn.png"
            style="width: 100px; height: 50px;" />
        <img alt="" onclick="Close()" src="/Close.png" />
        Division:<select class="dropdown" name="Division" data-ng-model='selectedDivision' data-ng-options='item.DivisionName for item in Divisions'></select>
        <span style="color: Red; font-weight: lighter;" ng-show="userForm.Division.$error.empty">Division is not selected</span>
        Year<select class="dropdown" data-ng-model='selectedYear' name="Year" data-ng-options='item.Year for item in Years'></select>
        <span style="color: Red; font-weight: lighter;" ng-show="userForm.Year.$error.empty">Year is not selected</span></div>
</div>
  The items in the dropdown are being pulled from sharepoint list and the code is all under one controller. On addAnswers Event the data is being stored in the list again in the same controller.

I would like to create a service and have different controllers to bind data to the dropdown list and a different controller to save the data. And below is the code I have written

        var myApp = angular.module('myApp', []);
       myApp.config(function ($httpProvider) {
//Enable cross domain calls
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
    });
   myApp.service('getItensforDropdownService', ['$http', function ($http) {
var list = function (username) {
    return $http({
        method: 'GET',
        url: username,
        withCredentials: true,
        dataType: 'json',
        headers: { "Accept": "application/json; odata=verbose" }

    });
}

return {
    Items: list
};
    }]);

And the Controllers are :

    myApp.controller('DivisionCtrl',    ['$scope', 'getItensforDropdownService',
function ($scope, getItensforDropdownService) {

    getItensforDropdownService.Items("/Division")
      .success(function (data, status, headers, config) {
          data.d.results.unshift({ DivisionName: '---Select---' });
          // do magic stuff with the result
          // (which is in the data param)
          $scope.Items = data.d.results;
          $scope.selectedOption = $scope.Items[0];
      })
    .error(function (data, status, headers, config) {
        $scope.getCallJSONResult = "data not retrieved";
    })
    }]);

However, I dont understand how do I pass the values of the selected dropdowns in the new controller on ng-click for Addanswers($event) Please let me know how do I get this to work.

Janet
  • 1,391
  • 14
  • 40
  • 62

2 Answers2

0

If you want to share data between views/controllers, you can use the getter/setter approach in a service. Below is a simple example that will hopefully be helpful and make sense.

When you click the button in the snippet below, Controller1 stores your selection (in this example, letters) in a service. You could then have any other controller retrieve these values from the service, and/or update the values. An example of how another controller can call these stored values is shown in Controller2 code below.

angular.module('ionicApp', ['ionic'])

.controller('Controller1', function($scope, divisionService) {
   
    $scope.firstList = ["a", "b", "c"];
    $scope.secondList= ["f", "g", "h"];

    $scope.first = "a";
    $scope.second = "f";
    
    $scope.set = function(first,second) {
       divisionService.setLetters(first,second);
       alert("First letter = " + first + " and Second letter =" + second + ". These have been updated in divisionService and can be called/updated by any other controller");
    }
})

.controller('Controller2', function($scope, divisionService) {
         
    $scope.get = function() {
       //get 'stored' letters from divisionService
       var selectedLetters = divisionService.getLetters();
       $scope.firstLetter = selectedLetters.firstLetter;
       $scope.secondLetter = selectedLetters.secondLetter;
    }
})

.factory('divisionService', function($http) {
   
 var selectedLetters = {}
 
    return {
 
        setLetters: function(firstLetter,secondLetter) {       
     selectedLetters.firstLetter = firstLetter;
            selectedLetters.secondLetter = secondLetter;
        },
        getLetters: function() {       
           return selectedLetters;
        }
    }
})
      
<html ng-app="ionicApp">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title>Ionic Template</title>
    <link href="http://code.ionicframework.com/1.0.0-beta.2/css/ionic.css" rel="stylesheet">
    <script src="http://code.ionicframework.com/1.0.0-beta.2/js/ionic.bundle.js">
    </script>
  </head>
  <body ng-controller="Controller1">
    </ion-content>
     <div>
         <select ng-model="first" ng-options="letter for letter in firstList "></select> 
         <select ng-model="second" ng-options="letter for letter in secondList "></select> 
         <button class="button button-small button-positive" ng-click="set(first,second)">Store these options in a service</button>
     </div>
    </ion-content>
  </body>
</html>
LJ.Wizard
  • 605
  • 1
  • 6
  • 10
0

At this point in your code, you are in fact returning a promise object rather than the results of the $http call, as you might expect.

return {
    Items: list
};

(list also represents an un-executed function, you never access the return value from it because you aren't referencing that function as list().. or you could define it as list = function(){ ... }()

your Items property is set to a promise of a response from a request - The solution below is how to do asynchronous external data correctly: use the function that deals with a successfully returned promise: .then(), and execute the GET request with myService.asyncFuncNameAsdf(), and use the then function on the returned promise to work with the data returned.

service

app.factory('myService', function($http) {
  return {
    asyncFuncNameAsdf: function() {
      return $http.get('test.json');  //1. this returns promise
    }
  };
});

controller

app.controller('MainCtrl', ['myService', '$scope', function( myService,$scope) {
    myService.asyncFuncNameAsdf().then(function(d) { //2. so you can use .then()
        console.log(d);
        $scope.data = d; // update {{data}} when AJAX complete
    });
}]);

second and third controllers communicating using a service

app.controller('SecondCtrl', ['myService', '$scope', '$timeout',function( myService, $scope, $timeout){ function( myService, $scope, $timeout){
    $scope.shared_property = myService.shared_property || "about to change";
    $timeout(function(){
        myService.shared_property = "Hello services";
    }, 3000); // 3 seconds later controller 2 and 3 will update
}]).controller('ThirdCtrl', ['myService', '$scope', '$timeout', function( myService, $scope, $timeout){
    $scope.shared_property = myService.shared_property || "Not updated yet"; // this will change from "not set yet" to the property after the second controller changes it
}]);

further reading

Community
  • 1
  • 1
J-Dizzle
  • 3,176
  • 6
  • 31
  • 49