问题是我必须管理从服务中检索到的口香糖球列表。当我对 HTML 中的元素进行硬编码时,我创建的指令似乎有效,但是当我尝试使用 ng-repeat 动态分配口香糖球时。
HTML
<div ng-controller="GumballsCtrl">
<h1>Working</h1>
<ul>
<li ng-repeat="gumball in Gumballs">
<div class="gumballColor{{gumball.color}}">{{gumball.color}}</div>
</li>
</ul>
<h1>Problem - Expecting the same result at the work version</h1>
<ul>
<li ng-repeat="gumball in Gumballs">
<mygumball id={{gumball.id}} color="{{gumball.color}}">{{gumball.color}}</mygumball>
</li>
</ul>
</div>
JavaScript
var myApp = angular.module('myApp', []);
function GumballsCtrl($scope, Gumballs) {
$scope.Gumballs = Gumballs;
}
myApp.factory('Gumballs', function () {
return [{
id: '1',
color: 'R'
}, {
id: '2',
color: 'G'
}, {
id: '3',
color: 'B'
}, {
id: '4',
color: 'Y'
}, {
id: '5',
color: 'G'
}];
});
myApp.directive('mygumball', function ($scope) {
return {
restrict: 'E',
scope: {},
link: function (scope, element, attrs) {
if (attrs.color !== '' && attrs.color !== undefined) {
scope.color = attrs.color;
} else {
scope.color = 'U';
}
},
replace: true,
template: "<div class='gumballColor{{color}}'>{{color}}</div>"
};
});
CSS
.gumballColorR {
font-size: 12px;
text-align: center;
padding: 2px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
border: solid 1px #CC0000;
background-color: #FF0000;
width: 15px;
height: 15px;
margin-left: 5px;
margin-top: 5px;
}
.gumballColorG {
font-size: 12px;
text-align: center;
padding: 2px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
border: solid 1px #00CC00;
background-color: #00FF00;
width: 15px;
height: 15px;
margin-left: 5px;
margin-top: 5px;
}
.gumballColorB {
font-size: 12px;
text-align: center;
padding: 2px;
color: #FFFFFF;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
border: solid 1px #0000CC;
background-color: #0000FF;
width: 15px;
height: 15px;
margin-left: 5px;
margin-top: 5px;
}
.gumballColorY {
font-size: 12px;
text-align: center;
padding: 2px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
border: solid 1px #CCCC00;
background-color: #FFFF00;
width: 15px;
height: 15px;
margin-left: 5px;
margin-top: 5px;
}
.gumballColorU {
font-size: 12px;
text-align: center;
padding: 2px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
border: solid 1px #CCCCCC;
background-color: #DDDDDD;
width: 15px;
height: 15px;
margin-left: 5px;
margin-top: 5px;
}
http://jsfiddle.net/i3sik/NGB9v/22/
传入指令时的 id 和 color 属性在使用 ng-repeat 传递时最终未定义,但在 HTML 中硬编码时有效。