Pass value in-between angular JS controller and se

2019-01-29 11:17发布

问题:

I am trying to get the user query from html using ng-click. I want to make a https call using the value which I fetch from ng-click. I can see the data in Alert--1 but in Alert--2 i get undefined. on internet I read that passing values using services is the best practice.Please correct me if I am wrong.

My controller

mainApp.controller('searchController',function($scope,searchString){

  $scope.getQuery = function(userq)  // its ng-click="getQuery(userq)" on Search button
  {
    $scope.userq=userq;
    alert('Alert--1'+userq);  // its working fine
    searchString.setSearchString(userq);
  };
});

//====================

mainApp.controller('fetchQueryResultController',function($scope,searchString){
   var searchStr = searchString.getSearchString();
   alert('Alert--2--'+searchStr);   //   Undefined
  // Later I'll use this value to fetch data from Watson search(Django) using $https call
});

My service:

mainApp.factory('searchString', function () {
    var qVal ;

    return {
        setSearchString:function (query) {
            qVal = query;
        },
        getSearchString:function () {
            return qVal;
        }
    };
});

Routing:

.when('/search', {
     templateUrl: "../static/views/seachResult.html",
     controller: "fetchQueryResultController"
  })

Is there any simpler way?

回答1:

Using a service is OK. Take a look at this, is quite clear for begginers:

https://egghead.io/lessons/angularjs-sharing-data-between-controllers

alert('Alert--2'+searchStr); is showing undefined because it is being executed before $scope.getQuery obviously. Controller's initialization is done before ng-init evaluates the expression.

In your case I believe it is better to fire an event when the data is set, so the second controller gets notified. This is being done with $on and $emit.

Here is a plunker with your example: http://plnkr.co/edit/97mVwbWmoOH3F7m8wbN0?p=preview

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

app.controller('searchController',function($scope,searchString){

  $scope.searchText;

  $scope.getQuery = function(userq)  // its ng-click="getQuery(userq)" on Search button
  {
    $scope.userq=userq;
    alert('Alert--1'+userq);  // its working fine
    searchString.setSearchString(userq, $scope);
  };
});

//====================

app.controller('fetchQueryResultController',function($scope, $rootScope, searchString){
   var searchStr = searchString.getSearchString;

   $scope.getData = function(){
     searchStr = searchString.getSearchString();
     alert('Alert--2--'+ searchStr); 
   }

   $rootScope.$on('dataModified', function(){
     $scope.getData();
   });

});

//====================

app.factory('searchString', function ($rootScope) {
    var qVal ;

    return {
        setSearchString:function (query) {
            qVal = query;
            $rootScope.$emit('dataModified');
        },
        getSearchString:function () {
            return qVal;
        }
    };
});


回答2:

this alert undefined

var searchStr = searchString.getSearchString();
 alert('Alert--2'+searchStr);  

becuase qVal hasn't set yet

qVal set when getQuery get called but that time alert2 already executed



回答3:

A simple solution is to have your factory return an object and let your controllers work with a reference to the same object:

JS:

// declare the app with no dependencies
var myApp = angular.module('myApp', []);


myApp.factory('searchString', function() {
  var qVal;

  return {
    setSearchString: function(query) {
      qVal = query;
    },
    getSearchString: function() {
      return qVal;
    }
  };
});

myApp.controller('setSearchController', function($scope, searchString) {
  $scope.setQuery = function(userq) {
    $scope.userq = userq;
    searchString.setSearchString(userq);
  };
});

myApp.controller('fetchQueryResultController', function($scope, searchString) {

  $scope.getQuery = function(user) {
    alert(searchString.getSearchString());
  };

});

HTML:

<div ng-app="myApp">
    <div ng-controller="setSearchController">
      <button ng-click="setQuery('Shohel')">Set</button>
    </div>
    <hr />
    <div ng-controller="fetchQueryResultController">
      <button ng-click="getQuery()">Get</button>
    </div>
  </div>

Here is similar fiddle