将字符串变量从控制器传递到指令 angularjs

pass string variable from controller to directive angularjs

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

控制器:

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

日期订单无效。如果我 console.log 它在我的控制器中我可以看到字符串,如果我然后在我的指令中记录它,它是未定义的。

有什么想法吗?

指令属性需要kebab-case, not 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 }}"

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

    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