2

I'm pretty new with angular and I've read a lot of threads here and googled this topic but I cannot get a clear answer. What I'm trying to do is pass a value that is not set until the user makes a selection, at which point my controller will make a call an asynchronous call and assign the result to a value in the controller. My directive's controller needs to access this value to conduct its logic.

Here is some similar code to what I have.

app.controller('testCtrl', function($scope){
    $scope.getData = function(){
       //getDataFunc is a method in a Factory, which is not shown here
       $scope.results = getDataFunc();
    }
}

app.directive('testDir', function(){
    return{
        restrict: 'AE',
        scope: {
            resultData:  '='
        },
        controller:['$scope', function($scope){
            //I need to be able to access the $scope.results from the parent controller

        }
    }
}

Any help would be appreciated.

  • So, you need to run controller code on directive only if `resultData` presents? – just-boris May 25 '15 at 22:24
  • Well you can always use `$rootScope` to access a variable or function. Maybe you should look here for a better understanding http://stackoverflow.com/a/21737230/4194436 – Michelangelo May 25 '15 at 22:35

2 Answers2

0

You are close:

Your markup should look something like:

<div ng-controller="testCtrl">
    <test-dir result-data="results"></test-dir>
</div>

app.controller('testCtrl', function($scope){
    $scope.getData = function(){
       //getDataFunc is a method in a Factory, which is not shown here
       $scope.results = getDataFunc();
    }
}

app.directive('testDir', function(){
    return{
        restrict: 'AE',
        scope: {
            resultData:  '='
        },
        controller:['$scope', function($scope){
            //I need to be able to access the $scope.results from the parent controller
             //$scope.resultData will always reflect the value of results here
             $scope.$watch('resultData', function(){
                 //called any time $scope.resultData changes
             });
        }
    }
}

You actually don't need two way binding, so this is how I would actually do it:

app.directive('testDir', function(){
    return{
        restrict: 'AE',
        scope: {
            resultData:  '&'
        },
        controller:['$scope', function($scope){
            //I need to be able to access the $scope.results from the parent controller
             //calling $scope.resultData() will always return the current value of the parent $scope.results

             $scope.$watch('resultData()', function(){
                 //called any time $scope.resultData() changes
             });
        }
    }
}
Joe Enzminger
  • 11,110
  • 3
  • 50
  • 75
0

Create a service with value and set/get methods to store the results of getDataFunc() and then inject that service into directive to get access to the value.

Adam S.
  • 145
  • 7