AngularJS filter is requiring two clicks before it filters results - angularjs

I am a beginner at angular. I am pretty certain I am doing this the completely incorrect way but because I finally have it "somewhat working" as it works on the second click I am stuck going in this direction and can't seem to figure out another way to do it.
The filter sorts on the second click because it is initialing as "undefined" before the first click and sets it based on that I believe.
In my html:
<div class="col-xs-12 col-sm-4 location-list" ng-repeat="key in careerlist.location">
<div class="locations" ng-click="careerlist.criteriaMatch()">{{key}}
</div>
</div>
<div class="col-xs-12">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-4 job-container" ng-repeat="job in careerlist.career | filter : searchText | filter: selectExperience | filter: careerlist.criteria.name">
<h2>
{{job.title}}
</h2>
<h3>
{{job.location}}
</h3>
<div class="job-description" ng-bind-html="job.description | limitHtml : 200">
</div>
<br><br>
<button>Read More</button>
</div>
<br><br>
</div>
</div>
In my controller:
cl.criteriaMatch = function( criteria ) {
jQuery(document).on('click', '.locations', function(){
cl.criteria = {};
console.log("just the element text " + jQuery(this).text());
cl.criteria.name = jQuery(this).text();
return function( criteria ) {
return criteria.name === criteria.name;
};
});
};

Use ng-click instead of jQuery#on('click'). Angular does not know that the filter should be updated.
Update
#Makoto points out that the click is bound twice. It very much looks like you should just remove the jQuery binding altogether. I would even go so far as suggesting removing jQuery from you project.

Related

In what scope is ng-repeat "as alias" available

I'm using angular 1.4.8. I want to save filtered result from ng-repeat and use it to determine whether to enable a "load more" button at the bottom of the list. I have looked at this question:
AngularJS - how to get an ngRepeat filtered result reference
And many others, they suggest to use "as alias" from ng-repeat, here's what my code looks like:
<ul class="media-list tab-pane fade in active">
<li class="media">
<div ng-repeat-start="item in items | limitTo: totalDisplayed as filteredResult">
{{item}}
</div>
<div class="panel panel-default" ng-repeat-end>
</div>
<div>
{{filteredResult.length}}
</div>
</li>
</ul>
<button ng-click="loadMore()" ng-show="totalDisplayed <= filteredResult.length">
more
</button>
However, I found filteredResult.length is displayed fine right after ng-repeat, but the button is never shown. If I try to display filteredResult.length in where the button is, it will show null.
So is there a rule for "as alias" scope? I've seen plenty of examples work but mine doesn't, what am I missing here?
EDIT:
The accepted answer uses controllerAs which indeed will resolve the problem. However, charlietfl's comment using ng-init to save filteredResult to parent scope is also very neat and that's the solution I use in my code eventually.
Probably some of classes in your <ul class="media-list tab-pane fade in active"> or <li class="media"> is selector for a directive that would have its own scope. So you store filteredResult in e.g. tab-pane's scope and then try to have access out of it's scope in outside of ul tag.
Try to use Controller as instead of scope:
angular
.module('plunker', [])
.controller('MainCtrl', function() {
vm = this;
// make an array from 1 to 10
var arr = [];
while (arr.length < 10) {
arr.push(arr.length + 1)
};
vm.items = arr;
vm.totalDisplayed = 5;
vm.filteredResult = [];
});
<body ng-controller="MainCtrl as main">
{{main.items}}
<ul class="media-list tab-pane fade in active">
<li class="media">
<div ng-repeat-start="item in main.items | limitTo: main.totalDisplayed as filteredResult">
{{item}}
</div>
<div class="panel panel-default" ng-repeat-end>
</div>
<div>
filteredResult = {{main.filteredResult = filteredResult}}
</div>
</li>
</ul>
<button ng-click="loadMore()" ng-show="main.totalDisplayed <= main.filteredResult.length">
more
</button>
</body>
http://plnkr.co/edit/drA1gQ1qj0U9VCN4IIPP?p=preview

Live search in AngularJS: updating the results

I want a live search: the results are queried from web api and updated as the user types.
The problem is that the list flickers and the "No results" text appears for a fraction of second, even if the list of results stays the same. I guess I need to remove and add items with special code to avoid this, calculating differences between arrays, etc.
Is there a simpler way to avoid this flicker at least, and probably to have possibility to animate the changes?
It looks like this now:
The html part is:
<div class="list-group">
<a ng-repeat="test in tests track by test.id | orderBy: '-id'" ng-href="#/test/{{test.id}}" class="list-group-item">
<h4 class="list-group-item-heading">{{test.name}}</h4>
{{test.description}}
</a>
</div>
<div ng-show="!tests.length" class="panel panel-danger">
<div class="panel-body">
No tests found.
</div>
<div class="panel-footer">Try a different search or clear the text to view new tests.</div>
</div>
And the controller:
testerControllers.controller('TestSearchListCtrl', ['$scope', 'TestSearch',
function($scope, TestSearch) {
$scope.tests = TestSearch.query();
$scope.$watch('search', function() {
$scope.tests = TestSearch.query({'q':$scope.search});
});
}]);
You should use ng-animate module to get the classes you need for smooth animation. For each ng-repeat item that's moved, added, or removed - angular will add specific classes. Then you can style those classes via CSS or JS so they don’t flicker.
An alternative way of doing what you require is to use the angular-ui bootstrap Typeahead component (check at the bottom of the post). It has a type-ahead-wait property in milliseconds and also a template url for customising it.
<div ng-app>
<div ng-controller="MyController">
<input type="search" ng-model="search" placeholder="Search...">
<button ng-click="fun()">search</button>
<ul>
<li ng-repeat="name in names">{{ name }}</li>
</ul>
<p>Tips: Try searching for <code>ann</code> or <code>lol</code>
</p>
</div>
</div>
function MyController($scope, $filter) {
$scope.names = [
'Lolita Dipietro',
'Annice Guernsey',
'Gerri Rall',
'Ginette Pinales',
'Lon Rondon',
'Jennine Marcos',
'Roxann Hooser',
'Brendon Loth',
'Ilda Bogdan',
'Jani Fan',
'Grace Soller',
'Everette Costantino',
'Andy Hume',
'Omar Davie',
'Jerrica Hillery',
'Charline Cogar',
'Melda Diorio',
'Rita Abbott',
'Setsuko Minger',
'Aretha Paige'];
$scope.fun = function () {
console.log($scope.search);
$scope.names = $filter('filter')($scope.names, $scope.search);
};
}

Angular drag and drop

I have two simple lists that I can drag my questions to and from. Each time I drag one of the questions it changes its "Active" status to true or false:
$scope.onDrop = function ($event, $data, array) {
if ($data.Active) {
$data.Active = false;
array.push($data);
}
else if (!$data.Active) {
$data.Active = true;
array.push($data);
}
};
This works great but I need to restrict the user from being able to drag and drop into the same list as they are dragging from since that also triggers the onDrop function.
I'm using : http://angular-dragdrop.github.io/angular-dragdrop/
I have just started out with drag and drop but from what I can tell of the documentation is that I have to use the drag-channel/drop-channel attributes , however I am having a hard time understanding how they actually work.
In my markup I have two panels like so:
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
Aktiva frågor
</div>
<div class="panel panel-body">
<ul class="dnd"
drag-channel="A"
drop-channel="A"
ui-on-drop="onDrop($event,$data,activeQuestions)">
<li ui-draggable="true" drag="aquestion"
on-drop-success="dropSuccessHandler($event,$index,activeQuestions)"
ng-repeat="aquestion in activeQuestions track by $index">
{{aquestion.Name}}
</li>
</ul>
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
Inaktiva Frågor
</div>
<div class="panel panel-body" >
<ul class="dnd"
drag-channel="B"
drop-channel="B"
ui-on-drop="onDrop($event,$data,inactiveQuestions)">
<li ui-draggable="true" drag="iquestion"
on-drop-success="dropSuccessHandler($event,$index,inactiveQuestions)"
ng-repeat="iquestion in inactiveQuestions track by $index">
{{iquestion.Name}}
</li>
</ul>
</div>
</div>
</div>
I have tried all kinds of combinations of A and B but none are working so obviously I seem to not understand the logic of them.
Or if this is not the best way to attack the problem please let me know of a better way. :)
Solved it by moving the Active logic into my code behind instead.

changing main content on ng-repeat item click

here is the plunker:
http://plnkr.co/edit/Qj2yxQuT7SZ19u3vuXyq?p=preview
like an inbox.
<div class="col-xs-4 leftnav">
<button class="btn btn-primary btn-block">Add News</button>
<br>
<article ng-repeat="x in issues | filter:query" ng-click="makeActive(i)">
<h4>{{x.title}}</h4>
<p>{{x.message | limitTo:numLimit}}</p>
Read More..
</article>
</div>
<div class="col-xs-8 main-content">
<h2>News</h2>
<hr>
<article ng-repeat="x in issues">
<h3 >{{x.title}}</h3>
<p>{{x.priority}}</p>
<p class="lead">{{x.author}} - 6/12/2014</p>
<!-- ng-if="x.author == 'Andy' " -->
<hr>
<p>{{x.message}}</p>
Read More
<hr>
</article>
</div>
having a list of items ng-repeat on the left, then selecting the main content (on the right) from the options, then displaying the full content as the main selection.
ng-if ? ng-show ?
not sure how well I've described this but it should be pretty obvious from the fiddle.
thanks in advance.
I modified your plnkr http://plnkr.co/edit/9qZsp2o22L5x1a0JofPy?p=preview
I create a currectIssue variable for your right content display.
In left content, Read More.. has been change to <a ng-click="showIssue(x)">Read More..</a>
updated plunk: http://plnkr.co/edit/hGsdkybRMoRct8VykCcB?p=preview
well, you might consider:
- use another scope variable to display the selected item from the object
- I'd use ng-if in this case as that will create/destroy the content as needed
// controller
$scope.selectIssue = function(x) {
$scope.issue = x;
}
$scope.selectIssue($scope.issues['1']);
//view
<article>
<h3 >{{issue.title}}</h3>
<p>{{issue.priority}}</p>
<p class="lead">{{issue.author}} - 6/12/2014</p>
<div ng-if="issue.author == 'Andy'">
<hr>
<p>{{issue.message}}</p>
Read More
<hr>
</div>
</article>

Get id of parent element of currently clicked element in AngularJS

How do I get the id of a parent element of currently clicked element in AngularJS?
<div id="d8" class="menutitles ng-scope" ng-repeat="title in list">
<div class="right" ng-click="showsubmenu($event)">+</div>
<div class="left" ng-click="showsubmenu($event)">Unit 9</div>
</div>
How to get the value d8 in showsubmenu($event) function?
Below is what I tried but it doesn't work
$scope.showsubmenu=function(obj)
{
alert(obj.target.parent.attributes.id)
}
It should be parentNode, not just parent:
alert(obj.target.parentNode.id);
Also attributes is redundant as you can access id property directly.
But note, that since you have ngRepeat, it will create invalid markup, since ids are going to be duplicated. You probably want to fix this too, maybe like this or use classes:
<div id="d8{{$index}}" class="menutitles ng-scope" ng-repeat="title in list">
<div class="right" ng-click="showsubmenu()">+</div>
<div class="left" ng-click="showsubmenu()">Unit 9</div>
</div>
<div id="d8" class="menutitles ng-scope" ng-repeat="title in list">
<div class="right" ng-click="showsubmenu()">+</div>
<div class="left" ng-click="showsubmenu()">Unit 9</div>
</div>
It should be enough :D
function showsubmenu($event){
$($event.target).parent();
}
Have a nice day
As an addition to Pedro's answer I'd say that using the jQuery method closest would be preferable.
function showsubmenu($event){
var parent = $($event.target).closest('.yourclass'); // or any selector you prefer
}

Resources