如何从指令访问工厂?
How can I access a factory from a directive?
我有一些导航栏项目应该只在用户通过身份验证时显示。下面的简化视图:
导航栏
<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
}
]);
不是分配给函数调用,而是分配函数(删除末尾的“()”。
我有一些导航栏项目应该只在用户通过身份验证时显示。下面的简化视图:
导航栏
<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
}
]);
不是分配给函数调用,而是分配函数(删除末尾的“()”。