【问题标题】:ng-show not working properly in angularjsng-show 在 angularjs 中无法正常工作
【发布时间】:2015-10-02 22:01:43
【问题描述】:

我想根据控制器内的属性值显示元素。

eReaderBook.directive("controlTools", function () {
return {
    replace : true,
    restrict : "E",
    templateUrl : "assets/directives/controlstools.html",
    controller : function ($scope) {
        $scope.visible = false;
    },
    link : function (scope, el, attr) {

       el.bind("mouseover",function()
        {
           console.log(scope.visible)
           scope.visible = true;
        });
        el.bind("mouseout",function()
        {
            console.log(scope.visible)
             scope.visible = false;
        })
    }
};

});

<div class="menuitem"><span class="glyphicon glyphicon-search"></span><span ng-show="visible" class="menutext">Toc</span></div>

在指令中,我有一个用$scope.visible = false 定义的控制器。页面加载时一切正常。我想在mouseover 上将状态更改为$scope.visible = truemouseout 上的$scope.visible = false。为什么scope.visible = true; 不影响ng-show

【问题讨论】:

  • DOM 事件在 Angular 之外。您需要使用 $scope.$apply() 通知 Angular 更改。 Angular 已经为此提供了指令,因此您无需创建新指令。
  • 您的事件处理发生在 $digest-cycle 之外。使用$apply 或更好的ngMouseenter
  • 为什么不使用ng-mouseover="visible = true"ng-mouseleave="visible = false"?我认为这更容易。例如。 &lt;span ng-show="visible" ng-mouseover="visible = true" ng-mouseleave="visible = false" class="menutext"&gt;Toc&lt;/span&gt;.

标签: angularjs


【解决方案1】:

You just forgot to add scope: true that is responsible to share scope.

return {
  replace: true,
  restrict: "E",
  scope: true,
  templateUrl: "assets/directives/controlstools.html",

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多