0

Goal: I need to execute a method in a directive template html , the method is a member of an object which is passed to directive scope.

I am trying to get "Hello, world!" output. Can some one help please.

html:

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

myApp.directive('passObject', function() {
    return {
        restrict: 'E',
        scope: { obj: '=' },
        template: '<div>Hello, {{obj.func1()}}!</div>'
    };
});

myApp.controller('MyCtrl', function ($scope) {
    $scope.obj = { func1: "$scope.function1.toString()" };
  
  $scoe.function1 = function() {
    return "world!";
  };
});
<div ng-controller="MyCtrl">
    <pass-object obj="obj"></pass-object>
</div>
Manohar
  • 153
  • 1
  • 1
  • 9

3 Answers3

1

First of all you need to define the function before you create the object. Second you need to pass the function definition not the function call to the object(without '()').

var myApp = angular.module('myApp',[]);
myApp.directive('passObject', function() {
    return {
        restrict: 'E',
        scope: { obj: '=' },
        template: '<div>Hello, {{obj.func1()}}!</div>'
    };
});

myApp.controller('MyCtrl', function ($scope) {
    $scope.function1 = function() {
        return "world!"; // here you can call .toString() if needed
    };
    $scope.obj = { func1: $scope.function1 };
});
<div ng-controller="MyCtrl">
    <pass-object obj="obj"></pass-object>
</div>
Vlad
  • 185
  • 1
  • 6
0
  1. "@" ( Text binding / one-way binding )
  2. "=" ( Direct model binding / two-way binding )
  3. "&" ( Behaviour binding / Method binding )

So you should user & instead of = and passing the function itself, not the whole object. I can not make work your shippet, not your directive without the function.

See more: What is the difference between '@' and '=' in directive scope in AngularJS?

Community
  • 1
  • 1
  • Thank you. I am planning to use "=", as I have a object with all required functions which needed in directive and also I need two-way binding. vlad's solution is working. – Manohar Dec 02 '15 at 23:33
0
var myApp = angular.module('myApp',[]);

myApp.directive('passObject', function() {
return {
    restrict: 'AE',
    scope: { obj: '&obj' },

    template: '<div>Hello, {{obj()}}!</div>'
};
});

 myApp.controller('MyCtrl', function ($scope) {

$scope.obj = { func1: $scope.function1 };

$scope.function1 = function() {
    return "world!";
};
});

<div ng-app="myApp">
 <div ng-controller="MyCtrl">
     <pass-object obj="function1()"></pass-object>
 </div>

You can also pass the function in the directive and call it.. this works for me ..

  • Thanks Jenil. I have tried this way I, it works fine. Since I have many arguments to be passed to directive so I was planning to use a object. I was looking for a solution by explicitly passing function as part of object and call it. I got the answer from vlad. – Manohar Dec 02 '15 at 23:31