如何从隔离范围指令调用控制器方法?

时间:2014-06-30 09:59:33

标签: javascript angularjs directive

我做错了什么?

点击状态块中的“Click me”文本后,应显示一个新字符串。 (实际上有4条新线,但只有2条)

(JSFiddle)

<div ng-app="myApp">
    <div ng-controller="myController">
        <button my-directive status="status" clickHandler="handler(message)">Click me</button>
        <pre>{{ status }}</pre>
    </div>
</div>

脚本:

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

app.controller('myController', ['$scope', '$timeout',
    function myController ($scope, $timeout) {

        $scope.status = 'Start controller.\n'; // update status
        $scope.someData = 'Hello from controller !!!\n';
        $scope.handler = function handler (message) {
            $scope.status += $scope.someData; // must update status, but doesn't do it
            $scope.status += 'Message from directive: ' + message; // must too
        }

    }]);

app.directive('myDirective', function myDirective () {
    return {
        scope: { clickHandler: '&', status: '=' },
        link: function postLink (scope, element, attr) {
            scope.status += 'Start link in myDirective.\n'; // update status
            element.on('click', function onClick (event) {
                scope.status += 'Click is fired.\n'; // update status
                scope.$apply(function scopeApply () {
                    scope.status += 'In apply context.\n'; // update status
                    scope.clickHandler('"I\'m from directive."\n');
                });
            });
        }
    }
});

1 个答案:

答案 0 :(得分:2)

HTML

属性名称应以短划线分隔:

<button my-directive status="status" click-handler="handler(message)">
    Click me
</button>

JS

应该通过传入一个对象来调用该方法:

scope.clickHandler({message:'"I\'m from directive."\n'});

<强> Updated Fiddle