我有一个在ng-repeat里面的指令。例如:
<div class="nx-owl-col" nx-owl-carousel-item ng-repeat="slider in slides track by $index">
<div class="clearfix nx-item-wrapper nx-shaddow1" ng- if="slider.nativeAdHome==='nativeAdHome'">
<nx-dfp-ad carousel-data="0"></nx-dfp-ad>
</div>
</div>
&#13;
我的指示:
(function() {
'use strict';
angular
.module(NgApp)
.directive('abc', ABC);
function ABC($compile) {
return {
restrict: "EA",
scope: {
},
link: function (scope, element, attrs) {
scope.count =0;
element.append("<div id='div-" + scope.count +"' style='height:250px; width:300px;'>");
$compile(element.contents())(scope)
scope.count++;
}
}
}
})();
&#13;
在ng-repeat&#34; slider.nativeAdHome&#34;中有条件,只要它为真,它将调用指令。我希望每次调用指令时都应该递增计数。如果它在ng-repeat中第一次调用,则计数值应为0,如果调用第二次计数值应为1等。 请解释我们如何实现这一目标。
答案 0 :(得分:1)
可以通过多种方式进行管理,其中一些方式:
{ count:1 }
(1)可能的解决方案 - https://jsfiddle.net/maciejsikora/31aqxmy3/(打开浏览器控制台以显示结果)。
(4)可能的解决方案https://jsfiddle.net/maciejsikora/sxn7nkrk/1/没有隔离范围(打开浏览器控制台以显示结果)。
(3)我展示如何管理第三个命令,我在指令函数中创建了局部变量count。变量仅在指令上可见。
var NgApp=angular.module("app",[]);
(function() {
'use strict';
angular
.module("app")
.controller("cont",Cont)
.directive('abc', ABC);
function Cont($scope){
//example data
$scope.slides=[
{
nativeAdHome:"nativeAdHome"
},{
nativeAdHome:"somethingElse",
},
{
nativeAdHome:"nativeAdHome"
},
{
nativeAdHome:"nativeAdHome"
}
];
};
function ABC($compile) {
//local variable - shared between all directive usage
var count=0;
return {
restrict: "EA",
link: function (scope, element, attrs) {
console.log("Current count = "+count);
count++;
}
};
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="cont">
<div class="nx-owl-col" nx-owl-carousel-item ng-repeat="slider in slides track by $index">
<div class="clearfix nx-item-wrapper nx-shaddow1" ng-if="slider.nativeAdHome==='nativeAdHome'">
<abc carousel-data="0"></abc>
</div>
</div>
</div>
答案 1 :(得分:0)
在控制器中执行ng-if比较。
在您的主控制器中
$scope.countNum= 0;
$scope.IsNativeAdHome = function(slider){
if(slider.nativeAdHome==='nativeAdHome'){
$scope.countNum++;
return true;
}
}
在HTML中
<div class="nx-owl-col" nx-owl-carousel-item ng-repeat="slider in slides track by $index">
<div class="clearfix nx-item-wrapper nx-shaddow1" ng-if="IsNativeAdHome(slider)">
<nx-dfp-ad carousel-data="0" count-num={{countNum}}></nx-dfp-ad>
</div>
</div>
指令
(function() {
'use strict';
angular
.module(NgApp)
.directive('abc', ABC);
function ABC($compile) {
return {
restrict: "EA",
scope: {
countNum:'@'
},
link: function (scope, element, attrs) {
scope.count = scope.countNum;
element.append("<div id='div-" + scope.count +"' style='height:250px; width:300px;'>");
$compile(element.contents())(scope)
scope.count++;
}
}
}
})();