Maher Maher - 4 months ago 17
AngularJS Question

How can compile scope ngClick in directive on ngRepeat

I have a directive, in this directive we compile ngRepeat as you see.

my problem is :

I can't call $scope.delete() from controller, and i don't know how can compile it in my directive.


Note: run the sample




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

app.controller("ctrl", function ($scope, $http) {
var root = "http://jsonplaceholder.typicode.com";

$scope.list = [];

$http.get(root + "/users").success(function (data) {
$scope.list = data;
});

///i can't call this scope
$scope.delete = function (item) {
alert("delete called");
}
});

app.directive("mydata", ["$compile", "$filter", function ($compile, $filter) {
return {
restrict: "A",
scope: {
list: "="
},
link: function (scope, element) {
var ngRepeat = element.find(".repeat").attr("ng-repeat", "item in list");
$compile(ngRepeat)(scope);
}
}
}]);

<!DOCTYPE html>
<html ng-app="app" ng-controller="ctrl">
<head>
<title></title>
</head>
<body>
<ul id="parent" mydata data-list="list">
<li class="repeat">
{{item.name}}
<button ng-click="delete()">delete</button>
</li>
</ul>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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




Answer

Don't know why u are trying to do stuffs like this but a quick solution for your code is to compile the ngRepeat with the controller's scope instead of the directive the scope;

$compile(ngRepeat)(scope.$parent);

Your delete() won't fire since u are creating an isolated scope on your my-data directive. The delete() method will not get inherited.

For more conception about isolated scope and scope inheritance, check https://docs.angularjs.org/guide/directive#isolating-the-scope-of-a-directive and https://docs.angularjs.org/guide/scope