将值从指令传递给控制器
下面是我的html模板:
Below is my html template:
<div ng-app="dr" ng-controller="testCtrl">
<test color1="color1" data-method="ctrlFn(msg)"></test>
</div>
以下是我的代码:
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>
为什么我会未定义而非某些人消息
您的代码几乎是正确的,但是您有几个问题这里:
Your code is almost correct, however you had several issues here:
<test color1="color1" data-method="ctrlFn(msg)"></test>
在这里传递 ctrlFn()
函数来自您的控制器,它带有一个未定义的参数 msg
,这会导致警报消息带有未定义文本。我建议将HTML代码修改为:
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>
请注意,我将 ctrlFn
作为变量,而不是函数。
Note that I pass the ctrlFn
as a variable, not function.
在你的指令代码中,我将范围绑定更改为 =
以确保 ctrlFn
将指向您的控制器功能。这也在指令的作用域和控制器(父)作用域之间建立了双向绑定。然后该指令的整个JS代码将如下所示:
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);
}
}
});
只需将&
替换为 =
。工作分叉: http://jsfiddle.net/L8masomq/
Just replacing the &
to =
. Working fork: http://jsfiddle.net/L8masomq/