Angularjs – How To Get Data Back From Angular Directive

angularjsangularjs-directiveangularjs-scope

i hope somebody could help me with a small example, because angular is driving me crazy 🙁

I'm making by first time a Formular that should follow this structure:
Angular APP

mainController
—->smallController1
——–>otherElements
—->smallController2
——–>otherElements
—->Directive1 (instance 1)
—->anotherSmallController
—->Directive1 (instance 2)

The Directive1 receives many attributes, and each instance will allow the selection of many options, and the result of the user interaction should be stored in an object, and that object should be accessed from mainController for each instance separately.

Does anyone have an example that work like that?

Thanks in advance,
John

Best Solution

The best way to get data back from directive is to attach a model to directive's self scope.

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

app.controller('mainController', 
                [
  '$scope', 
  function($scope){
    $scope.myObj = "Initial Value";
  }
]);

app.directive('dirName', [
  function(){
    return {
      restrict : 'A',
      scope : {
        obj : "=ngModel"
      },
      link : function(scope, element, attrs){
        scope.obj = attrs.newValue;
      }
    };
  }
]);
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body ng-app="app" ng-controller="mainController">
  <input dir-name ng-model="myObj" new-value="Final Value">
</body>
</html>

You can check this bin as well : http://jsbin.com/fuqujo/1/edit?html,js,output