我有一些导航栏项目,只有当用户通过身份验证时才会显示。简化视图如下:
导航栏
<body ng-controller="mainController as main">...
<li ng-show="main.isSecretAgent"><a href="#secret">THIS IS A SECRET</a></li>
</body>
工厂
tardis.factory('bgData', [function() {
var persistentData = {
isSecretAgent: false,
};
return {
checkIfSecretAgent: function(){
return persistentData.isSecretAgent
}
}
}]);
主控制器
tardis.controller('mainController',["$scope","bgData",
function($scope,bgData) {
$scope.isSecretAgent = bgData.checkIfSecretAgent()
}
]);
假设bgData
工厂中设置的isSecretAgent
值可能会随着用户操作而更改,我如何设置我的ng-show
以基于此进行更新?
您可以通过这种方式获得函数。。。
导航栏
<body ng-controller="mainController as main">...
<li ng-show="main.isSecretAgent()"><a href="#secret">THIS IS A SECRET</a></li>
</body>
主控制器
tardis.controller('mainController',["$scope","bgData",
function($scope,bgData) {
$scope.isSecretAgent = function {
return bgData.checkIfSecretAgent()
}
}
]);
此外,如果使用ng-if
会更好,因为在ng-show
的情况下,元素仍将存在于DOM中。
如果您使用函数调用编写ng show:
<span ng-show="isSecretAgent()">Show me when I'm a secret agent</span>
然后,每次运行摘要时,都会检查工厂内的值。这就是你所需要做的。
除了你应该更改你的isSecretAgent来调用如下函数:
tardis.controller('mainController',["$scope","bgData",
function($scope,bgData) {
$scope.isSecretAgent = bgData.checkIfSecretAgent
}
]);
与其分配给函数调用,不如分配函数(删除末尾的"()"。