Sharing a variable between controllers in angular.js

前端 未结 1 1112
生来不讨喜
生来不讨喜 2020-11-29 03:29

I\'m new to angular and I\'m wondering how I can share a variable between controllers in angular. I\'m using the following scripts -

In Main.js:

fun         


        
相关标签:
1条回答
  • 2020-11-29 03:51

    Use a service and inject it to both controllers and refer your scope vars to the services variable.

    Example:

    angular.module("yourAppName", []).factory("myService", function(){
    
      return {sharedObject: {data: null } }
    
    });
    
    function MainCtrl($scope, myService) {
      $scope.myVar = myService.sharedObject;
    }
    
    function SearchCtrl($scope, $http, myService) {
      $scope.myVar = myService.sharedObject;
    }
    

    In your template do:

    {{myVar.data}}
    

    See an example Uses Angular v1.1.5

    The reason you put it in an inner object is to preserve your references, if you keep it without a "sharedObject", and change that object, your binding will be pointing to the old reference and wouldn't show anything in the template.

    0 讨论(0)
提交回复
热议问题