内部元素不知道指令范围

时间:2014-04-08 09:32:56

标签: angularjs angularjs-directive angularjs-scope

我希望在鼠标悬停在<cart>指令上时显示下拉列表。 mouseover事件肯定会触发并将scope.showDropdown更改为true,但<div class="cart">似乎并未意识到这一点,即使我设置了showDropdown的范围到'='。我是一个有自定义指令的初学者。我在这里缺少什么?

.directive('cart', ['Cart', function(Cart){
return {
    templateUrl: './templates/cart.html',
    restrict: 'E',
    scope: {
        showDropdown: '='
    },
    link: function(scope, element, attrs){
        scope.showDropdown = false;
        scope.items = Cart.getItems;
        element.bind('mouseenter', function(){
            scope.showDropdown = true;
        });
        element.bind('mouseout', function(){
            scope.showDropdown = false;
        })
    }
}
}]);

app.controller('cartController', ['$scope', function($scope){
    $scope.showDropdown = false;
}])

cart.html

<cart ng-controller="cartController">
Cart
    <div class="cart" ng-show="showDropdown">
        <ul>
            <li rg-repeat="item in items">{{item.name}}</li>
        </ul>
    </div>
</cart>

2 个答案:

答案 0 :(得分:0)

您需要将其作为参数传递给您的指令:

 <div class="cart" show-dropdown="showDropdown" ng-show="showDropdown">

但我认为最好的解决方案是将ng-show放在模板中。你不能隐藏指令的所有元素,否则你怎么能触发鼠标悬停事件?

答案 1 :(得分:0)

原来问题是我没有应用我对范围所做的更改。最后,我不需要使用控制器或属性。

.directive('cart', ['Cart', function(Cart){
return {
    templateUrl: './templates/cart.html',
    restrict: 'E',
    scope: '=',
    link: function(scope, element, attrs){
        scope.items = Cart.getItems;
        element.bind('mouseenter', function(){
            scope.$apply('showDropdown = true');
        });
        element.bind('mouseout', function(){
            scope.$apply('showDropdown = false');
        })
    }
}
}]);

<cart>
Cart
    <div class="cart ng-hide" ng-show="showDropdown">
        <ul>
            <li rg-repeat="item in items" class="ng-binding"></li>
        </ul>
    </div>
</cart>