指令内的随机 ng-show
random ng-show within directive
我无法弄清楚...我是 angular 的新手,如果我做了一些愚蠢的事情,我深表歉意。
我想使用 ng-show 随机显示部分指令。
html:
<div ng-controller="MyCtrl">
<div ng-repeat="color in colors">
<my-directive color="color"></my-directive>
</div>
</div>
控制器:
function MyCtrl($scope) {
$scope.colors = [
{color: "red", stuff: "1"},
{color: "blue", stuff: "2"},
{color: "yellow", stuff: "3"}
];
}
指令:
myApp.directive('myDirective', function() {
return {
restrict: 'EA',
scope: {
color: '=',
showText: '@'
},
template: 'test <p ng-show="showText">{{color.color}} {{color.stuff}}</p>',
controller: function ($scope, $element) {
$scope.showText = Math.random() < 0.5;
}
}
});
<p>...</p>
从来不显示,为什么?
那是因为您在范围 属性 showText
上有一个 (@
) 文本绑定。当指令呈现时,它会评估控制器并在隔离范围对象上设置 属性 值,但随后会评估文本绑定并覆盖范围 属性 showText
即使没有值绑定到它。所以基本上你设置的随机布尔值被 @
绑定 属性 (undefined/null) 覆盖,它是假的将总是隐藏 p
标签。
您可以只从指令设置中删除 showText: '@'
,如果您不需要它,或者可以通过使用 $timeout
将 属性 值的设置推迟到下一个摘要周期.
我无法弄清楚...我是 angular 的新手,如果我做了一些愚蠢的事情,我深表歉意。
我想使用 ng-show 随机显示部分指令。
html:
<div ng-controller="MyCtrl">
<div ng-repeat="color in colors">
<my-directive color="color"></my-directive>
</div>
</div>
控制器:
function MyCtrl($scope) {
$scope.colors = [
{color: "red", stuff: "1"},
{color: "blue", stuff: "2"},
{color: "yellow", stuff: "3"}
];
}
指令:
myApp.directive('myDirective', function() {
return {
restrict: 'EA',
scope: {
color: '=',
showText: '@'
},
template: 'test <p ng-show="showText">{{color.color}} {{color.stuff}}</p>',
controller: function ($scope, $element) {
$scope.showText = Math.random() < 0.5;
}
}
});
<p>...</p>
从来不显示,为什么?
那是因为您在范围 属性 showText
上有一个 (@
) 文本绑定。当指令呈现时,它会评估控制器并在隔离范围对象上设置 属性 值,但随后会评估文本绑定并覆盖范围 属性 showText
即使没有值绑定到它。所以基本上你设置的随机布尔值被 @
绑定 属性 (undefined/null) 覆盖,它是假的将总是隐藏 p
标签。
您可以只从指令设置中删除 showText: '@'
,如果您不需要它,或者可以通过使用 $timeout
将 属性 值的设置推迟到下一个摘要周期.