将对象传递给指令内部的ng-click

时间:2016-05-25 12:57:54

标签: angularjs angularjs-directive

我正在努力让对象传递给指令然后在ng-click属性中使用。 HTML和指令如下。如上所述,ng-class属性被正确呈现""作为ng-class="{ 'my-class': selectedItem === {"FirstName":"John","LastName":"Snow"} }"

但是,ng-click指令被错误地呈现为ng-click="selectedItem = value"

我无法在ng-click指令中使用{{value}},或者会引发错误,指出Token '{' invalid key at column 17 of the expression [selectedItem = {{value}}] starting at [{value}}]."

我尝试使用链接而不是模板并使用scope.value来切换它。这将返回[object Object],因为此时我将连接字符串。

HTML:

<table ng-table="tableParams">
    <tr ng-repeat="item in $data">
        <td>
            <check-box ng-model="selectedItem" behavior="radio" value="item"></check-box>
        </td>
    </tr>
</table>

指令:

angular.module('check-box.directive', [])
    .directive('checkBox', checkBoxDirective);

    function checkBoxDirective() {
    return {
        scope: {
            value: '='
        },
        restrict: 'E',
        replace: true,
        template: template
    };

    function template(element, attributes) {

        var baseHtml = '<button type="button" ';
        var ngClass = 'ng-class="{ \'my-class\': ' + attributes.ngModel + ' === {{value}} }"';
        var ngClick = 'ng-click="' + attributes.ngModel + ' = value"';

        return baseHtml + ngClass + ngClick + '></button>';
    }
}

1 个答案:

答案 0 :(得分:0)

看看这个解决方案:

    var ngClick = `ng-click= "${attributes.ngModel} = ${value}"`;