简体   繁体   中英

Passing values from directive to controller

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/

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/

its bit of a quirk... read more about it here

what you need to do is - change below

scope.fromDirectiveFn(scope.hello);

to

 scope.fromDirectiveFn({'msg' : scope.hello});

the variable names should be same in caller & callee

Actually, the code is correct. But, the value of msg which is getting undefined. Thus, you ctrlFn(msg) is returning as undefined. adding the 'msg' property and assigning the scope.hello will resolve the problem. Check the improved [Jsfiddle][1] here.

scope.fromDirectiveFn({'msg': scope.hello}); 

http://jsfiddle.net/imsabmaverick81/j2K7N/215/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM