AngularJS:从指令设置范围变量

angularjs: setting a scope variable from directive

本文关键字:范围 变量 设置 指令 AngularJS      更新时间:2023-09-26

首先我想要的:我有一系列缩略图。当我单击一个时,我希望该特定缩略图显示在更大的div 中,并带有其描述。(稍后:应动画化)。

现在我有指令和控制器,但我不知道如何设置适当的变量!

所以一些代码:第一个 HTML:这是本节的根.jade文件。我有一条指令叫product.

section
    .detail-view(ng-show="vm.showDetail")
      .prod-desc(ng-bind="vm.detailPic")
      .prod-img(ng-bind="vm.detailDesc")
    product.col-xs-12.product_tile(ng-repeat="item in vm.products", item="::item")

如您所见,product 指令是ng-repeat的一部分;因此,我想显示调整大小的图像的div 在迭代之外.detail-view )。

产品指令:

'use strict';
ProductDirective.$inject = ['ShopCart', '$animate', 'User'];
function ProductDirective(ShopCart, $animate, User) {
    return {
        restrict: 'E',
        scope: {
            item: '='
        },
        template: require('./product.html'),
        link: link
    };
    function link(scope, element) {            
        scope.toggleDetails = toggleDetails; 
     }
     function toggleDetails() {
            if (!scope.isSelected && isBlurred()) return;
            scope.vm.detailPic  = scope.item.photo;
            scope.vm.detailDesc = scope.item.prod_description;
            scope.vm.isSelected = !scope.isSelected;
            scope.showDetail = !scope.showDetail;
            var action = scope.isSelected ?
     }
}

现在我想用大图像更新的div 在迭代之外 - 因此超出了指令的范围。如何设置showDetailshowDescshowPic的值?

由于我正在使用具有值vmcontrollerAs,我认为我可以做scope.vm.detailPic = scope.item.photo;,就像在其他解决方案中一样,我已经看到在根对象上设置属性时,它将被传播......但我得到

无法设置未定义的属性"详细信息图片"

目前,有效的(但对我来说看起来有点奇怪)是这样的,toggleDetails()

scope.$parent.$parent.vm.detailPic = scope.item.photo;
scope.$parent.$parent.vm.detailDesc = scope.item.prod_description;
scope.$parent.$parent.vm.showDetail = !scope.$parent.$parent.vm.showDetail