Bill
Bill

Reputation: 19298

Angular js pass Data from Config Controller to other Controll

I have a situation i would like to pass data from control (within config) to the external controller. I have tried factory to pass data around, however after the data gets changed, it still remain 0 (not sure where i have done wrong) is there a way i can pass the data to the navCtrl after the DynamicController change? Thanks for help

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

    app.factory('idService', function(){
        var id = 0;
        var itemsService = {};

        itemsService.set = function(val) {
            id = val;
        };
        itemsService.get = function() {
            return id;
        };

        return itemsService;
    })

    app.controller('navCtrl', ['$scope', 'idService', function($scope, idService){
        $scope.disable = 'disabled';
        console.log(idService.get());
    }])

    app.config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/:page/:id', {
            template: '',
            controller: DynamicController
        });
    }])

    function DynamicController($scope, $routeParams, $http, idService)
    {
        var templateUrl = '/index.php?controller=lead&action=' + $routeParams.page + '&id=' + $routeParams.id;
        idService.set($routeParams.id);
        $http.post(templateUrl).success(function(data){
            $('#content').html(data);            
        })
    }

Upvotes: 0

Views: 578

Answers (1)

CalM
CalM

Reputation: 532

If you want the value to keep in sync - regardless of the load order, then you should use the $scope. That's what it was designed for.

Depending on what you want to do with the value, you have a number of options.

Display the value in the view

$scope.displayId = idService.get() or better still, why not just add the id the $rootScope and access it from there?

You want to be notified when the value changes in navCtrl, so you can do further processing

You can either use $rootScope.$broadcast('routeParamIdChanged', id) in DynamicCtrl and then listen for the change using $scope.$on('routeParamIdChanged, fn(ev, id){}) or you could create a $watch which checks the service.

Upvotes: 1

Related Questions