您好我是Angular JS的新手,我正在尝试通过显示或隐藏填充屏幕的div来创建“灯箱”。但是,“ng-click”事件和div位于不同的模板上。
第一个模板(div应该出现在哪里):
<body ng-app="portfolio" ng-controller="lightboxController" >
<div ng-show="lightbox" class="lightbox">
<p ng-click="checkLightbox()">go back</p>
<p>{{message}}</p>
</div>
<div class="top-menu">
<a href="#portfolio" class="top-menu-button">portfolio</a>
<a href="#about" class="top-menu-button">about</a>
<a href="#contact" class="top-menu-button">contact</a>
</div>
<div id="content-wrapper">
<div id="main-content">
<div ng-view></div>
</div>
</div>
</body>
相关控制人:
app.controller('lightboxController', function($scope) {
$scope.checkLightbox = function(){
$scope.lightbox;
lightbox= !lightbox;
console.log(lightbox);
};
$scope.message = 'Everyone come and see how good I look!';
});
第二个模板(ng-click事件所在的位置):
<div class="grid">
<div class="grid-item dreiD video" ng-click="checkLightbox()">
<img src="data/portfolio/logo-animation/thumb.gif" class="thumb"/>
错误消息显示: ReferenceError:未定义灯箱
答案 0 :(得分:0)
我不确定你的checkLightbox()方法应该做什么。
但是如果你想让这个可重用,那么最好的解决方案就是将checkLightbox功能重构为可重用的指令。
这样的事情:
function checkLightbox() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.on('click', function() {
// add your code here
})
}
}
}
app.directive('checkLightbox', checkLightbox);
现在,您可以在视图的任何位置使用此功能,方法是在任意位置添加check-lightbox
属性。
<div class="grid">
<div class="grid-item dreiD video" check-lightbox>
<img src="data/portfolio/logo-animation/thumb.gif" class="thumb"/>
答案 1 :(得分:0)
执行以下操作: 你的HTML看起来像
<body ng-app="app" ng-controller="lightboxController" >
<div ng-show="lightbox" class="lightbox">
<p ng-click="checkLightbox()">go back</p>
<p>{{message}}</p>
</div>
<div class="top-menu">
<a href="#portfolio" class="top-menu-button">portfolio</a>
<a href="#about" class="top-menu-button">about</a>
<a href="#contact" class="top-menu-button">contact</a>
</div>
<div id="content-wrapper">
<div id="main-content">
<div ng-view></div>
</div>
</div>
<div class="grid">
<div class="grid-item dreiD video" ng-click="checkLightbox()">
<img src="data/portfolio/logo-animation/thumb.gif" class="thumb"/>
</div>
</div>
</body>
角度控制器看起来像:
var app = angular.module('app', []);
app.controller('lightboxController', function($scope) {
$scope.checkLightbox = function(){
$scope.lightbox;
$scope.lightbox= !$scope.lightbox;
console.log(lightbox);
};
$scope.message = 'Everyone come and see how good I look!';
});
运行此功能
答案 2 :(得分:0)
只要你需要在任何其他控制器中使用它们,就在$ rootScope中声明函数或变量。
答案 3 :(得分:-1)
将您的控制器转换为工厂并在$ rootScope级别创建范围:
app.factory('lightboxController', ['$rootScope', function($rootScope) {
$rootScope.checkLightbox = function(){
$rootScope.lightbox;
lightbox= !lightbox;
console.log(lightbox);
};
$rootScope.message = 'Everyone come and see how good I look!';
}]);