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/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…