Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  29] [ 2]  / answers: 1 / hits: 15593  / 9 Years ago, fri, june 26, 2015, 12:00:00

Below is my html template:



<div ng-app=dr ng-controller=testCtrl>
<test color1=color1 data-method=ctrlFn(msg)></test>
</div>


Below is my code:



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

app.controller(testCtrl, function($scope) {
$scope.ctrlFn = function(arg) {
alert(arg);
}

});
app.directive('test', function() {
return {
restrict: 'E',
scope: {
fromDirectiveFn: '&method'
},
link: function(scope, elm, attrs) {
//Way One
scope.hello = some message;
scope.fromDirectiveFn(scope.hello);
}
}
});

<div ng-app=dr ng-controller=testCtrl>
<test color1=color1 data-method=ctrlFn(msg)></test>
</div>


Why am i getting undefined instead of some message



Below is a fiddle
http://jsfiddle.net/j2K7N/27/


More From » angularjs

 Answers
5

Your code is almost correct, however you had several issues here:



<test color1=color1 data-method=ctrlFn(msg)></test>


Here you pass the ctrlFn() function from your controller, which takes one undefined argument msg, that causes the alert message with undefined text. I suggest to modify the HTML code to this:



<test color1=color1 data-method=ctrlFn></test>  


Note that I pass the ctrlFn as a variable, not function.



In your directive code, I changed the scope binding to = to make sure that the ctrlFn will point to your controller function. This also sets up a two-way binding between the directive's scope and the controller (parent) scope. Then the whole JS code of the directive will look like this:



app.directive('test', function() {
return {
restrict: 'E',
scope: {
fromDirectiveFn: '=method'
},
link: function(scope, elm, attrs) {
//Way One
scope.hello = some message;
scope.fromDirectiveFn(scope.hello);
}
}
});


Just replacing the & to =. Working fork: http://jsfiddle.net/L8masomq/


[#66036] Wednesday, June 24, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
manuel

Total Points: 747
Total Questions: 96
Total Answers: 95

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
;