Neo
Neo

Reputation: 16219

how to pass parameter and get values from custom directive in angular js?

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example11-production</title>


  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.min.js"></script>
  <script src="script.js"></script>  
</head>
<body ng-app="docsSimpleDirective">
  <div ng-controller="Controller">
  <div my-customer></div>
</div>
</body>
</html>

script.js

(function(angular) {
  'use strict';
angular.module('docsSimpleDirective', [])
  .controller('Controller', ['$scope', function($scope) {
    $scope.customer = {
      name: 'Naomi',
      address: '1600 Amphitheatre'
    };
  }])
  .directive('myCustomer', function() {
    return {
      template: 'Name: {{customer.name}} Address: {{customer.address}}'
    };
  });
})(window.angular);

I want pass value to directive and based on key want to retrieve value from controller method.

pass value here <div my-customer="FirstName"></div> FirstName is the key want to pass it to directive and get FirstName value from controller method.

how can i achieve this?any similar thread ?

Upvotes: 0

Views: 1962

Answers (1)

aludvigsen
aludvigsen

Reputation: 5981

To pass values to a custom directive, you need to specify it in the directive.

.directive('myCustomer', function() {
  return {
    scope: {
      myvariable: "="
    },
    template: 'Name: {{myvariable.name}} Address: {{myvariable.address}}'
  };
});

now you can:

<!-- customer is an object from your controller -->
<div my-customer myvariable="customer"></div>

There are different ways to pass values. You can use @, = and &. They all work different. Read this great SO post regarding all the types of bindings you can do.

JsFiddle Demo

Remember that the '=' means that the binding is bi-directional. It is a reference to a variable to the parent scope. In other words, when you change the variable in the directive, it will be changed in the parent scope as well.

Upvotes: 4

Related Questions