Graham Graham - 5 months ago 62
AngularJS Question

Angular custom directive with isolate scope not firing ng-click function

I have the following Angular custom directive code:

Template (ReviewStandards.html)

<div class="review-standard" ng-repeat="standard in standards">
<button ng-click="mark(standard)">Mark Complete</button>
</div>


JS

app.directive("reviewStandards", function ($parse, $state) {
return {
restrict: "A",
templateUrl: function (elements, attrs) {
return "/Scripts/App/Directives/Templates/ReviewStandards.html";
},
transclude: false,
scope: {
standards: "="
},
replace: true,
link: function (scope, elem, attrs) {

scope.mark = function (standard) {
alert();
};
}
};
});


The directive is used as:

<div review-standards standards="review.ReviewStandards"></div>


Where
standards
is just a JSON array of
standard
objects.

Problem is that the the
ng-click
is not firing the function when the button is clicked. The scope is isolated - is this something to do with this or the fact that the button is in an
ng-repeat
?

Answer

Try This, "i just remove the Replace from your codes"

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

        app.controller("ctrl", function ($scope) {

            $scope.data = [
                { name: "a" },
                { name: "b" }
            ];


        });

        app.directive("reviewStandards", function () {
            var template = "<div class=\"review-standard\" ng-repeat=\"standard in standards\"> " +
                "<button ng-click=\"mark(standard)\">Mark Complete</button>" +
                "</div>";
            return {
                restrict: "A",
                transclude: false,
                template: template,
                scope: {
                    standards: "="
                },
                link: function (scope, elem, attrs) {

                    scope.mark = function (standard) {
                        alert();
                    };
                }
            };
        });
<!DOCTYPE html>
<html ng-app="app" ng-controller="ctrl">
<head>
    <title></title>
</head>
<body>

    <div review-standards standards="data"></div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


</body>
</html>