MikeW
MikeW

Reputation: 1620

Use result of jQuery selector in Angular expression

I am trying to bind the expression used in a ng-show attribute to the result of a jQuery selector. The reason for this is that I need to hide/show an element based on the presence of another element (ng-view)

The markup I have currently is

<div ng-view id="partialView"></div>

<div ng-show="$('#partialView').length === 0">
    <h1>MAIN CONTENT</h1>
</div>

and when this is rendered I get:

<!-- ngView: -->
<div ng-show="$('#partialView').length === 0" class="ng-hide">...</div>

when the ng-view is not provided, or

<div ng-view id="partialView">...</div>
<div ng-show="$('#partialView').length === 0" class="ng-hide">...</div>

the expression in the ng-show is not being evaluated (or maybe simply not re-evaluated).

My question is

Is this the correct way to bind the ng-show to the presence of another element in the DOM, and if it is the correct way to do it, what is wrong with my syntax that is stopping it from working?

Upvotes: 0

Views: 483

Answers (3)

MikeW
MikeW

Reputation: 1620

Thanks to the help of @basant-rules and @martin-glennon I moved the logic into the controller, so now my controller has a function defined on it's scope:

var LandingPageController = function ($scope) {
    $scope.noPartialView = function () {
        return $('#partialView').length ===0;
    };
};

and the view looks like:

<div ng-view id="partialView"></div>

<div ng-show="noPartialView()">
    <h1>Main Content</h1>
</div>

Upvotes: 0

Basant Rules
Basant Rules

Reputation: 807

ng-show work with scope that you defined in controller.

you should define scope with jQuery or scope.

like

$scope.partialView=0 //or any thing that you want.

<div ng-show="partialView === 0" class="ng-hide">...</div>

Upvotes: 1

Martin Glennon-Brown
Martin Glennon-Brown

Reputation: 291

Your view does not know what $() is, in your controller assign the jquery $ to $scope element e.g. $scope['$'] = $

Upvotes: 0

Related Questions