我正在尝试将控制器中的字符串变量传递给使用隔离范围的指令。我设法传递了一个对象和一个函数,但似乎无法正常工作!
控制器:
angular.module("app").controller("myCtrl", function($scope)
{
//data that needs to be passed to the directive
$scope.myParams = $scope.params; //object
$scope.myDateOrder = $scope.dateOrder; //string
});
html:
<div ng-controller="myCtrl">
<my-dir params="myParams" dateOrder="myDateOrder">
</my-dir>
</div>
指令:
angular.module("app").directive("myDir", [
function() {
return {
restrict: "E",
scope: {
checkPermissions: "&", //pulled from contact directive -> method/function
params: "=", //passed object though from smwAddCustomerBank -> two way binding
dateOrder: "@" //passed string value from smwAddCustomerBank -> one way binding
},
dateOrder无法正常工作。如果将console.log记录在控制器中,则可以看到字符串,如果随后将其记录到指令中,则该字符串是未定义的。
有什么想法吗?
答案 0 :(得分:1)
指令属性必须为kebab-case,而不是camelCase:
<div ng-controller="myCtrl">
̶<̶m̶y̶-̶d̶i̶r̶ ̶p̶a̶r̶a̶m̶s̶=̶"̶m̶y̶P̶a̶r̶a̶m̶s̶"̶ ̶d̶a̶t̶e̶O̶r̶d̶e̶r̶=̶"̶m̶y̶D̶a̶t̶e̶O̶r̶d̶e̶r̶"̶>̶ ̶
<my-dir params="myParams" date-order="myDateOrder">
</my-dir>
</div>
有关更多信息,请参见AngularJS Developer Guide - Directive Normalization。
谢谢-对于其他为此感到困扰的人,我需要做的全部改变是:
params="myParams", date-order="{{ myDateOrder }}"
为避免使用插值({{ }}
),请对"<"
使用单向绑定,而不要对"&"
使用属性绑定 :
scope: {
checkPermissions: "&", //pulled from contact directive -> method/function
params: "=", //passed object though from smwAddCustomerBank -> two way binding
̶d̶a̶t̶e̶O̶r̶d̶e̶r̶:̶ ̶"̶@̶"̶
dateOrder: "<" //passed string value from smwAddCustomerBank -> one way binding
}
然后只需:
<my-dir params="myParams" date-order="myDateOrder">
有关更多信息,请参见AngularJS Comprehensive Directive API Reference - scope。