Skip to content

Instantly share code, notes, and snippets.

@erikwj
Created November 17, 2015 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikwj/9778681bd2b6b15ad74c to your computer and use it in GitHub Desktop.
Save erikwj/9778681bd2b6b15ad74c to your computer and use it in GitHub Desktop.
angulardirective calling external functions
var app = angular.module('DirectivesModule', []);
app.controller('CustomersController', ['$scope', function ($scope) {
var counter = 0;
$scope.customer = {
name: 'David',
street: '1234 Anywhere St.'
};
$scope.customers = [{name:"Goliath",street:"Temple Mountain"}];
$scope.addCustomer = function (name) {
console.log(name);
counter++;
$scope.customers.push({
name: (name) ? name : 'New Customer' + counter,
street: counter + ' Cedar Point St.'
});
};
$scope.changeData = function () {
counter++;
$scope.customer = {
name: 'James',
street: counter + ' Cedar Point St.'
};
};
}]);
angular.module('DirectivesModule').directive('customerDirective', function () {
return {
restrict: 'EA',
scope: {
datasource: '=',
add: '&',
},
controller: function ($scope) {
$scope.addCustomeriati = function () {
//Call external scope's function
var name = 'New Customer Added by Directive';
$scope.add()(name);
};
},
template: '<button ng-click="addCustomeriati()">Change Data</button><ul>' +
'<li ng-repeat="cust in datasource">{{ cust.name }}</li></ul>' +
'<p> Bla Bla </p>'
};
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></script>
<meta charset=utf-8 />
<title>Modals</title>
</head>
<body ng-app='DirectivesModule'>
<div ng-controller='CustomersController'>
<div customer-directive datasource="customers" add="addCustomer"></div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment