___ ___ erkimt Sharing the variable $ scope from one controller to another with parameters in AngularJS ______ qstntxt ___

I have this:

%pre%

I wanted my second controller to get the $ scope.getIdJobs variable and save it to a variable again. How can I do this?

%pre%

app.js

%pre%     
______ azszpr165042 ___

A simple solution is to have a factory that returns the value that you need (an object for example): JS:

%pre%

HTML:

%pre%

Demo: link

When applications get larger, more complex, and harder to test, you may not want to expose the entire object of a factory in this way, but instead give limited access for example via getters and setters:

%pre%

With this approach controllers consume the service with new values and use $ watch to observe the changes:

%pre%

HTML:

%pre%

Demo: link

    
______ azszpr164875 ___

I'm a beginner too but I'll try to help you by giving two tips:

  • There is %code% that holds information and when loaded can be passed from controllers to controllers, much used for IDs.

  • Another way would be to store this %code% in a service and then use it in other controllers by calling it: %code%

  • ______ azszpr164891 ___

    You can put the products variable in $ rootScope, so you can access it for $ rootScope anywhere. But I advise you to use the ui-router to make the parameters pass, it gets more cohesive and with less chances of you having undesirable variable value substitution problems, or something like that.

    You should set the parameter in your state:

    %pre%

    And it will pass it this way:

    %pre%     
    ______ azszpr165044 ___

    Good,

    In my opinion it is advisable to create a %code% for the date, which will be %code% , where you can encapsulate the date and its %code% . Then just call the %code% you need in the controllers.

    Here's the example in this jsfiddle

    %pre%

    In the controller that accesses %code% you call the %code% method.

    %pre%

    In the second controller, just declare %code% or if necessary you can filter again with a new id.

    %pre%

    In this way, you can clear the %code% , and everything relative to that date can be reached in %code% and %code% easily.

    Or you will have the option of %code% , which also works for what you want.

    About routers, I advise you to take a look at ui-router , a far superior tool in my understanding.

        
    ___

    1

    I have this:

    $scope.products = [];
    
        $http.get('app/components/job/controller/teste.json').success(function (resource) {
            $scope.products  = resource;
    });
    
    $scope.getIdJobs = function(getIdJobs) {
        var result = $filter('filter')( $scope.products, {id:getIdJobs})[0];
        console.log(result);
        console.log(getIdJobs);
    }
    

    I wanted my second controller to get the $ scope.getIdJobs variable and save it to a variable again. How can I do this?

    app.controller("job_detail", ["$scope", "$http", "$location", "$route","$rootScope", "$routeParams", function($scope, $http, $location, $route, $rootScope, $routeParams) {
    
        //image home
        $rootScope.home = false;
    
        //change color background in page job
        $scope.isOnCertainPage = function() {
            return $location.path() === "/job";
        };
    
    
        $http.get('app/components/job/controller/teste.json').success(function (resource) {
            $scope.products = resource;
            $scope.jobId = $routeParams.jobId;
            //console.log($scope.jobId);
        }); 
    
        console.log($scope.title, $scope.localidade, $scope.products);
    
    }]);
    

    app.js

    app.config(function($routeProvider, RestangularProvider){
        $routeProvider
            .when("/",{
                templateUrl: "app/components/home/views/job_offers.html",
                controller: "employerCtrl"
            })
            .when("/job" , {
                templateUrl: "app/components/job/views/job.html",
                controller: "job"
            })
            .when("/job/:jobId" , {
                templateUrl: "app/components/job/views/jobdetail.html",
                controller: "job_detail" 
            })   
            .otherwise({
                redirectTo: '/'
            });
    
    
    });
    
        
    asked by anonymous 11.11.2016 / 10:55

    4 answers

    2

    A simple solution is to have a factory that returns the value that you need (an object for example): JS:

    // Inicializa a aplicação
    var myApp = angular.module('myApp', []);
    
    // Cria a factory para acompartilhar o valor da variável
    myApp.factory('Fact', function(){
      return { Value: 'Foo' };
    });
    
    // 2 Controllers utilizando o mesmo valor
    myApp.controller('FirstCtrl', function( $scope, Fact ){
      $scope.Alpha = Value;
    });
    
    myApp.controller('SecondCtrl', function( $scope, Fact ){
      $scope.Beta = Value;
    });
    

    HTML:

    <div ng-controller="FirstCtrl">
        <input type="text" ng-model="Alpha.Value">
        First {{Alpha.Value}}
    </div>
    
    <div ng-controller="SecondCtrl">
    <input type="text" ng-model="Beta.Value">
        Second {{Beta.Value}}
    </div>
    

    Demo: link

    When applications get larger, more complex, and harder to test, you may not want to expose the entire object of a factory in this way, but instead give limited access for example via getters and setters:

    myApp.service('Data', function(){
    var data =
        {
            Value: ''
        };
    
        return {
            getValue: function () {
                return data.Value;
            },
            setValue: function (Value) {
                data.Value = Value;
            }
        };
    });
    

    With this approach controllers consume the service with new values and use $ watch to observe the changes:

    myApp.controller('FirstCtrl', function( $scope, Data ) {
    
        $scope.Value = '';
    
        $scope.$watch('Value', function (newValue, oldValue) {
        if (newValue !== oldValue) Data.setValue(newValue);
        });
    });
    
    myApp.controller('SecondCtrl', function( $scope, Data ){
    
        $scope.$watch(function () { return Data.getValue(); }, function (newValue, oldValue) {
            if (newValue !== oldValue) $scope.Value = newValue;
        });
    });
    

    HTML:

    <div ng-app="myApp">
    
        <div ng-controller="FirstCtrl">
            <input type="text" ng-model="Value">
            <br>Controller 1 : <strong>{{Value}}</strong>
        </div>
        <hr>
        <div ng-controller="SecondCtrl">
            Controller 2: {{Value}}
        </div>
    
    </div>
    

    Demo: link

        
    11.11.2016 / 20:25
    1

    I'm a beginner too but I'll try to help you by giving two tips:

  • There is $localStorage that holds information and when loaded can be passed from controllers to controllers, much used for IDs.

  • Another way would be to store this $scope.getIdJobs in a service and then use it in other controllers by calling it: job_detail.get();

  • 11.11.2016 / 11:25
    0

    You can put the products variable in $ rootScope, so you can access it for $ rootScope anywhere. But I advise you to use the ui-router to make the parameters pass, it gets more cohesive and with less chances of you having undesirable variable value substitution problems, or something like that.

    You should set the parameter in your state:

    .state('contacts', {
        url: "/contacts",
        params: {
            param1: null
        },
        templateUrl: 'contacts.html'
    })
    

    And it will pass it this way:

    <a ui-sref="contacts({param1: value1})">View Contacts</a>
    
    $state.go('contacts', {param1: value1})
    
        
    11.11.2016 / 12:28
    0

    Good,

    In my opinion it is advisable to create a factory for the date, which will be Objecto , where you can encapsulate the date and its métodos . Then just call the propriedades you need in the controllers.

    Here's the example in this jsfiddle

    myApp.factory('myService', function() {
     return {
      data:[{id:1,content:''},{id:2,content:''},{id:3,content:''}, {id:4,content:''},{id:5,content:''},{id:6,content:'Restante Objecto...'},{id:7,content:''},{id:8,content:''},{id:9,content:''},{id:10,content:''}],
      result:{},
      filterById:function(id){
    
        //Estou a dar declarar o THIS numa variavel porque vou usa-lo dentro do forEach
        var that = this;
    
        that.data.forEach(function(item){
          if(item.id===id){that.result=item;}
        });
      }
     };
    });
    

    In the controller that accesses routerParams you call the filterById() method.

    function FirstCtrl($scope,myService) {
      var RouterParamsId = 6;
      myService.filterById(RouterParamsId);
      $scope.job = myService.result;
      console.log()
    }
    

    In the second controller, just declare result or if necessary you can filter again with a new id.

    function SecondCtrl($scope,myService) {
      $scope.job = myService.result;
    }
    

    In this way, you can clear the controllers , and everything relative to that date can be reached in controllers and directives easily.

    Or you will have the option of $rootScope , which also works for what you want.

    About routers, I advise you to take a look at ui-router , a far superior tool in my understanding.

        
    11.11.2016 / 20:34