Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

what i m doing: simple html file shows first page , in this page i have one title and button, initially i set $scope.index = 0. so, we set first position of array. when we click on next button it finds firstCtrl and first.html page. in this controller i update $scope.index by 1. so, my question is when i update $scope.index of myCtrl then $scope.index is changed on another controller i wants to change myCtrl. is it possible ? if it is then help me.

index.html:

<body ng-controller="myCtrl">
     <div id="navbar">
        <div class="setToggle">
          <input id="slide-sidebar" type="checkbox" role="button" />
          <label for="slide-sidebar"><span class="glyphicon glyphicon-menu-hamburger"></span></label>
        </div>
        <div class="setQuestion">
          <h2>{{surveys[index].questionTitle}}</h2>
        </div>
      </div>
      <div class="content-wrapper" class="container-fluid">
        <div class="sidebar-left">
          <div class="first">
            <ul ng-repeat="cat in surveys[index].category" class="list-unstyled" ng-hide="checkSubCategoryValueIsNull.length">
              <li class="category">
                <a ng-click="expand=!expand">
                  <span class="glyphicon" ng-class="{'glyphicon-plus': !expand, 'glyphicon-minus': expand}">
                    {{cat.categoryName}}
                  </span>
                </a>
              </li>
              <ul ng-repeat="subcategory in cat.categoryItemDto" class="list-unstyled">
                <li ng-show="expand">
                  <label class="label-style-change">
                    <input type="checkbox" ng-click="toggleSelectionCheckbox(surveys[index], subcategory)" ng-model="subcategory.selectValue" ng-disabled="disableCheckbox">
                    <span class="subcategory-item" ng-disabled="disableCheckbox">{{subcategory.subCategoryName}}</span>
                  </label>
                </li>
              </ul>
            </ul>
          </div>
          <div class="second">
            <input type="button" name="Submit" value="Submit" ng-click="submitSelection()" ng-hide="hideSubmitButton" ng-disabled="!selections[index].length">
            <input type="button" name="Edit" value="Edit" ng-click="EditSelection()" ng-show="hideEditButton">
          </div>
        </div>
        <div class="portfolio">
          <div id="main">
            <div ng-view></div>
          </div>
        </div>
      </div>
</body>

controller.js

(function() {

  var app = angular.module("app.controllers", ["app.service"]);

  app.controller("myCtrl", ["$scope", "$http", "$location", "$timeout", "surveyService", "Data",

    function ($scope, $http, $location, $timeout, surveyService, Data) {

      surveyService.getData(function(dataResponse) {

          $scope.surveys = dataResponse;

          $scope.selections = [];

          /* create 2d array mannually */
          var numInternalArrays = $scope.surveys.length;
          for (var i = 0; i < numInternalArrays; i++) {
            $scope.selections[i] = [];
          };

          $scope.index = 0;
          var toggleCheckboxFlag = 0;

          /* PRIVATE FUNCTION
              for find value from selections array and replace it
            */
          function findAndRemove(array, property, value) {
            array.forEach(function(result, index) {
              if(result[property] === value) {
                array.splice(index, 1);
                toggleCheckboxFlag = 1;
              }
            });
          }

          $scope.toggleSelectionCheckbox = function (QuestionId, value) {
            toggleCheckboxFlag = 0;
            if (!value) return;
            findAndRemove($scope.selections[$scope.index], 'categoryId', value.subCategoryId);
            if (toggleCheckboxFlag != 1) {
              $scope.selections[$scope.index].push({
                questionId: QuestionId.questionId,
                categoryId: value.subCategoryId,
                categoryName: value.subCategoryName,
                storeId: 1,
                comment: ""
              });
            }
          };

          $scope.submitSelection = function() {
            $scope.value = $scope.selections[$scope.index];
            $scope.hideSubmitButton = true;
            $scope.disableCheckbox = true;
            $scope.hideEditButton = true;

            $location.path("/question/1");
          }

      });

        $scope.EditSelection = function() {

          $scope.hideEditButton = false;
          $scope.hideSubmitButton = false;
          $scope.disableCheckbox = false;
          $scope.value = false;
        }

        $scope.$watch('index', function (newValue, oldValue) {

            if (newValue !== oldValue) Data.setIndex(newValue);
        });
      console.log("controller", Data.getIndex())
    }]);

})();

app.js

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

app.config(['$routeProvider', function($routeProvider) {

  $routeProvider
    .when('/question/1', {
      templateUrl: 'views/first.html',
      controller: 'sidebarCtrl'
    })
    .when('/question/2', {
      templateUrl: 'views/second.html',
      controller: 'mainCtrl'
    })
    .otherwise({
        redirectTo: '/'
    });
}]);

first.html

<div id="content-wrapper" ng-show="value">
  <div class="col-lg-offset-1 col-lg-8 col-md-12 col-sm-12 col-xs-12">
    <h2 class="subCategoryLabel"><span class="label">{{value[inc].categoryName}}</span></h2>
  </div>
  <div class="row">
    <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
      <button class="btnNext" ng-hide="inc == 0" ng-click="prev()">
        <i class="glyphicon glyphicon-menu-left"></i>
      </button>
    </div>
    <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
      <form name="myForm">
        <div ng-repeat="item in surveys[index].optionCategoryItemDto" class="formStyle">
          <label class="text-center">
            <input type="radio" name="radio" id="{{item.itemId}}" ng-value="item.itemId" ng-model="selections[index][inc].answer" required>
              {{item.itemName}}
          </label>
        </div>
        <br/>
        <br/>
      </form>
    </div>
    <div class="col-lg-3 col-lg-offset-1 col-md-offset-1 col-md-3 col-sm-4 col-xs-4">
      <button class="btnNext" ng-hide="selections[index].length == inc + 1" ng-disabled="myForm.radio.$error.required" ng-click="next()">
        <i class="glyphicon glyphicon-menu-right"></i>
      </button>
      <button class="btnNext" ng-show="selections[index].length == inc + 1" ng-disabled="myForm.radio.$error.required" ng-click="nextQuestion()">
        <i class="glyphicon glyphicon-forward"></i>
      </button>
    </div>
  </div>
  <div class="col-lg-offset-3 col-lg-4 col-md-offset-3 col-md-6 col-sm-offset-3 col-sm-6 col-xs-4">
    <textarea type="text" id="text"  class="form-control txtArea" ng-model="selections[index][inc].comment" placeholder="Write comment..."></textarea>
  </div>
</div>

sidebarCtrl.js

in this controller i update $scope.index when we call nextQuestion(). here $scope.index increment by one and $watch function also get latest value of index. but myCtrl is not update. i wants to update myCtrl.

    (function() {

   var app = angular.module("app.controllers");

   app.controller("sidebarCtrl", ['$scope', "$location", "Data", function($scope, $location, Data) {

      $scope.inc = 0;

      $scope.next = function() {
        $scope.inc += 1;
      }

      $scope.prev = function() {
        $scope.inc -= 1;
      }

      $scope.nextQuestion = function() {
        $scope.index += 1;
        $location.path("/question/2");
      }

       $scope.$watch('index', function (newValue, oldValue) {
         console.log("SASAS", newValue)
          if (newValue !== oldValue) Data.setIndex(newValue);
      });

   }]);

})();

service.js

(function() {

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

    app.service("surveyService", function($http) {

      this.getData = function (callbackFunc) {
        $http({
            method: "GET",
            data: {something: true},
            contentType: 'application/json',
            dataType: 'jsonp',
            url: "http://localhost:8080/TheSanshaWorld/sfcms/fetch-survey-details"
          }).success(function(data){
            callbackFunc(data);
        }).error(function(){
           alert("error");
        });
      };

      this.setData = function(value) {
        if (confirm('Do you wanna to submit?')) {
          $http.post("http://localhost:8080/TheSanshaWorld/sfcms/save-survey-result-data", value).success(function(data, status) {
            window.open("../index.html","_self");
          });
         } else {
           return false;
         }
      };

    });

      app.factory('Data', function () {

        var data = {
            Index: ''
        };

        return {
            getIndex: function () {
                return data.Index;
            },
            setIndex: function (index) {
                data.Index = index;
                console.log("service", data.Index)
            }
         };
      });

})();
share|improve this question
    
basically you need to create a service/factory that would share data amongst your application components – Pankaj Parkar Jan 19 at 7:56
    
i tried with services but although myCtrl is not update. – tushar balar Jan 19 at 7:59
    
This article might be useful: objectpartners.com/2013/08/21/… – Michał Komorowski Jan 19 at 8:00
    
    
You can make use of $broadcast and $emit events – Himanshu Jan 19 at 9:40
up vote 0 down vote accepted

Because sidebarCtrl is nested within myCtrl, therefore you can reach myCtrl $scope.index from sidebarCtrl using it $scope.$parent.index,

Try it by test: add any parameter value to myCtrl $scope.name='Bob'; then log it in sidebarCtrl console.log($scope.$parent.name); you should see printed 'Bob'. Do the same with index.

share|improve this answer
    
Thank you, @innovarerz , it's soled my issue. – tushar balar Feb 3 at 7:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.