首页 > 解决方案 > 如何纠正以下代码的解析错误

问题描述

html代码是:

<div ng-controller="myController">
    <input type="input" ng-model="title" />
    <br/>
    <p class="jm-find" title1="title" title2="spell('fe')"></p>
</div>

Javascript代码:

var app = angular.module('app', []);

app.controller("myController", function ($scope) {
    $scope.title = "binding";    
    $scope.spell = function(ele){
        console.log("me "+ele);
    }
});

app.directive("jmFind", function () {
    return {
        replace: true,
        restrict: 'C',
        transclue: true,
        scope: {
            title1: "=",
            title2: "&"
        },
        template: "<div><button ng-click={{title2}}>{{title1}}</button></div>"
    };
});

我试图了解 Angularjs 自定义指令中的“ & ”用法。我遵循了几个示例,但缺少调用该spell函数的正确语法。

JSFiddle 链接:http: //jsfiddle.net/k03ozLts/

标签: angularjs

解决方案


调用使用表达式 ( &) 绑定的 AngularJS 表达式:

app.directive("jmFind", function () {
    return {
        scope: {
            title1: "=",
            title2: "&"
        },
        ̶t̶e̶m̶p̶l̶a̶t̶e̶:̶ ̶"̶<̶d̶i̶v̶>̶<̶b̶u̶t̶t̶o̶n̶ ̶n̶g̶-̶c̶l̶i̶c̶k̶=̶{̶{̶t̶i̶t̶l̶e̶2̶}̶}̶>̶{̶{̶t̶i̶t̶l̶e̶1̶}̶}̶<̶/̶b̶u̶t̶t̶o̶n̶>̶<̶/̶d̶i̶v̶>̶"̶
        template: "<div><button ng-click='title2()'>{{title1}}</button></div>"
    };
});

推荐阅读