gpt4 book ai didi

javascript - 将字符串变量从 Controller 传递到指令 angularjs

转载 作者:行者123 更新时间:2023-12-01 01:29:16 25 4
gpt4 key购买 nike

我正在尝试将字符串变量从我的 Controller 传递到使用隔离范围的指令。我已经成功地传递了一个对象和一个函数,但似乎无法让它工作!

Controller :

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
},

日期订单不起作用。如果我在 Controller 中console.log它,我可以看到该字符串,如果我然后将其记录在我的指令中,它是未定义的。

有什么想法吗?

最佳答案

指令属性需要为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 .

<小时/>

Thank you - for anyone else that struggles with this, the full change I needed to make is: params="myParams", date-order="{{ myDateOrder }}"

要避免使用插值 ( {{ }} ),请使用 "<"单向绑定(bind)而不是使用 "&" 进行属性绑定(bind) :

    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 .

关于javascript - 将字符串变量从 Controller 传递到指令 angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53450789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com