Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Get Data Back From Angular Directive

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

like image 784
user3425557 Avatar asked Jan 19 '15 11:01

user3425557


2 Answers

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

like image 95
Neeraj Verma Avatar answered Nov 13 '22 17:11

Neeraj Verma


Use emit to send data to parent controller. It may be receiver because listening to event. Read about on emit and broadcast. In your child controller or directive use:

$scope.$emit('myEvent', object);

This sends object to all parent controllers. In parent controller use:

$scope.$on('myEvent', function(event, obj) { console.log(obj); });

To listen to emitted object.

like image 20
changtung Avatar answered Nov 13 '22 17:11

changtung