我看不出要弄清楚...我是角度的新手,如果我在做一些愚蠢的事情,很抱歉。
我想使用 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>
从不显示,为什么?
http://jsfiddle.net/oxr4c9ub/2/
这是因为您在 scope 属性 showText
上有一个 (@
) 文本绑定。当指令呈现时,它会计算控制器并在隔离的作用域对象上设置属性值,但随后它会计算文本绑定并覆盖 scope 属性showText
即使没有绑定到它的值也是如此。所以基本上你设置的随机布尔值被@
绑定属性(undefined/null)覆盖,如果 falsy 将始终隐藏p
标签。
如果您不需要它,您可以从指令设置中删除showText: '@'
,或者可能通过使用 $timeout
将属性值的设置推迟到下一个摘要周期。
小提琴