javascript - Passing values from directive to controller -
below html template:
<div ng-app="dr" ng-controller="testctrl"> <test color1="color1" data-method="ctrlfn(msg)"></test> </div>
below 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 1 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 getting "undefined" instead of "some message"
below fiddle http://jsfiddle.net/j2k7n/27/
your code correct, had several issues here:
<test color1="color1" data-method="ctrlfn(msg)"></test>
here pass ctrlfn()
function controller, takes 1 undefined argument msg
, causes alert message "undefined" text. suggest modify html code this:
<test color1="color1" data-method="ctrlfn"></test>
note pass ctrlfn
variable, not function.
in directive code, changed scope binding =
make sure ctrlfn
point controller function. sets two-way binding between directive's scope , controller (parent) scope. whole js code of directive this:
app.directive('test', function() { return { restrict: 'e', scope: { fromdirectivefn: '=method' }, link: function(scope, elm, attrs) { //way 1 scope.hello = "some message"; scope.fromdirectivefn(scope.hello); } } });
just replacing &
=
. working fork: http://jsfiddle.net/l8masomq/
Comments
Post a Comment