Passing values from directive to controller

时间:2015-06-26 09:38:54

标签: javascript angularjs

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/

3 个答案:

答案 0 :(得分:13)

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/

答案 1 :(得分:2)

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

答案 2 :(得分:0)

实际上,代码是正确的。但是,msg的值是未定义的。因此,ctrlFn(msg)将返回undefined。 添加&#39; msg&#39;属性和分配scope.hello将解决问题。在这里检查改进的[Jsfiddle] [1]。

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

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