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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With