Reputation: 167
I'm not sure if this is an angularjs bug or if I am doing something wrong, but when i create a directive using an isolate scope as well as a compile function to programmatically modify the template, the wrong scope is used. What's interesting is that if I change the ng-repeat to item in users
, which should not work as I am using an isolate scope...it actually works. Even more confusing...this code actually works correctly in angular 1.1.3. Anyone know whats going on?
Fiddles:
Not working in angular 1.2.3 - http://jsbin.com/iPIbubA/12/edit
Working in angular 1.1.3 as is - http://jsbin.com/iPIbubA/7/edit
Working in angular 1.2.3 with "item in users" http://jsbin.com/iPIbubA/15/edit
For example:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Demo Blog</title>
</head>
<body>
<div ng-app="app" class="container">
<h1>Blog Demo</h1>
<div class="row" ng-controller="main">
<collection items="users">
{{ $index + 1 }} - {{ item.name}} / {{ item.email }}
</collection>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
</body>
</html>
var app = angular.module('app', [ ]);
app.controller("main", function($scope) {
$scope.users = [
{ name : "bob", email : "[email protected]" },
{ name : "joe", email : "[email protected]" }
];
});
app.directive("collection", function() {
return {
restrict : "E",
scope : {
"items" : "="
},
compile : function(el, attrs) {
var itemTemplate = el.text();
// if I change ng-repeat to "item in users" it works!
el.html('<ul><li ng-repeat="item in items">' + itemTemplate + '</li></ul>');
}
};
});
Upvotes: 3
Views: 1621
Reputation: 43947
Use transclude
:
app.directive("collection", function() {
return {
restrict : "E",
scope : {
"items" : "="
},
template : '<ul><li ng-repeat="item in items">
<span ng-transclude></span></li></ul>',
transclude : true
};
});
Upvotes: 1