Angular JS:在第二个控制器中更改数据时更新控制器

时间:2016-01-19 07:51:48

标签: angularjs model-view-controller angularjs-service angularjs-controller

我在做什么: 简单的html文件显示第一页,在这个页面我有一个标题和按钮,最初我设置$ scope.index = 0.所以,我们设置数组的第一个位置。当我们点击下一个按钮时,它会找到firstCtrl和first.html页面。在这个控制器中我更新$ scope.index 1.所以,我的问题是当我更新myCtrl的$ scope.index然后$ scope.index在另一个控制器上更改我想要更改myCtrl。可能吗 ?如果它是帮助我。

的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

在这个控制器中,当我们调用nextQuestion()时,我会更新$ scope.index。这里$ scope.index增加1和$ watch函数也获得索引的最新值。但是myCtrl没有更新。我想更新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)
            }
         };
      });

})();

1 个答案:

答案 0 :(得分:1)

因为 sidebarCtrl 嵌套在 myCtrl 中,因此您可以从到达 myCtrl $ scope.index > sidebarCtrl 使用它 $ scope。$ parent.index

通过测试尝试:将任何参数值添加到myCtrl $ scope.name ='Bob'; 然后将其记录在sidebarCtrl console.log($ scope。$ parent.name);你应该看到打印'鲍勃'。对索引执行相同的操作。