Using existing JS function in angular ng-repeat - javascript

I previously had a javascript function onclick="submitDynamicSku()" but we have recently started converting to Angular to use the controller to build off of and i want to be able to pass this function through since it is part of the my ng-repeat.
Example:
onclick="submitDynamicSku('x', document.getElementById('y').value, false, true);"
I wanted to try:
onclick="submitDynamicSku(product.sku, document.getElementById('{{ product.id').value, false, true);"
Current Code:
$scope.submitSku = function(sku,id,false,true) {
submitDynamicSku(sku, document.getElementById(id).value, false, true);
function submitDynamicSku(sku, cnt, recurringOrder, viewCart) {
jQuery("#dynamicAsstName").val("");
jQuery("#dynamicSku").val(sku);
jQuery("#dynamicSkuCount").val(cnt);
jQuery("#setRecurringOrder").val(recurringOrder);
jQuery("#viewCart").val(viewCart);
if (viewCart == false) {
jQuery("form[name='dynamic_add_to_cart_form']")
.submit(function() {
this.action = "";
return true;
});
}
jQuery("form[name='dynamic_add_to_cart_form']").submit();
}
}
<%--Angular Block--%>
<li ng-repeat="product in products">
<div class="prod-img ">
<img ng-src="{{ product.imagePath }}" alt="{{ product.imageAlt }}" ng-class="{{ product.selector }}" />
</div>
<div class="prod-info">
<h2>{{ product.name}}</h2>
<h3>{{ product.price }}</h3>
<p>{{ product.description }} </p>
<a class="fancybox" href="#prodDesc-{{product.id}}">More Information »</a>
<div class="prod-cart">
<span class="qty-amt">QTY: <input value="1" id="{{ product.id }}" /> BOX</span>
<button href="javascript:void(0);" ng-click="submitSku(product.sku,product.id,false, true)">Add to Cart</button>
</div>
</div>
</li>

Assuming you have apply ng-repeat on div
HTML:
<div ng-repeat="product in products ">
<button ng-click="submitDynamicSku(product.sku,product.id,false, true)">{{product}}"</button>
</div>
Controller:
.controller('products', ['$scope', function($scope) {
$scope.products=[];
$scope.submitDynamicSku = function(sku,id,false,true) {
.......
}
}]);

Create the function inside your controller like this:
$scope.submitDynamicSku = function(pID){
var elm = document.getElementById(pID);
....
}
Then in the HTML use ng-click: (assume you use ng-repeat on product)
ng-click="submitDynamicSku(product.id)"

/* Inside the Controller */
$scope.submitSku = function(sku,id) {
submitDynamicSku(sku, id, false, true);
};
/* HTML */
<a ng-click="submitSku(product.sku, product.id);">...</a>

Related

How to count total results with ajax?

Have a problem with total count of ajax searche's results.
There is a mistake "Method Illuminate\Database\Eloquent\Collection::total does not exist." if I use directive for example
<div class="searched-item">
{{ __('main.res_found') }} {{$sfilms->total()}} {{ __('main.res_results') }}
</div>
How to fix it correctly?
blade template:
#if($sfilms)
#if($sfilms->count())
<div class="searched-item">
{{ __('main.res_found') }} {{$sfilms->count()}} {{ __('main.res_results') }}
</div>
#else
<div class="searched-item">
{{ __('main.res_found') }} 0 {{ __('main.res_results') }}
</div>
#endif
#foreach($sfilms as $sfilm)
<div class="search-hits">
<ol class="search-hits-list">
<li class="search-hits-item">
<a href="{{ url('films/'.$sfilm->film_id) }}">
<div class="search-img-wrapper">
#if(!is_null($sfilm->films->poster))
<img src="{{$sfilm->films->poster}}" alt="poster" class="news_movies-img">
#else
{{-- <img class="news_movies-img" src="{{ url('/img/no_poster.jpg') }}" alt="poster"/>--}}
<img src="{{asset('storage/poster/' . $sfilm->films->id . '.jpg')}}" alt="poster" class="news_movies-img">
#endif
</div>
<div class="search-hits-wrapper">
<div class="hit-title">
<h3>{{ $sfilm->title }}</h3>
</div>
<div class="hit-title">
<h4>{{ $sfilm->films->orig_title }}</h3>
</div>
<span>
<p class="poster_genre-link">{{ $sfilm->films->country}} {{ $sfilm->films->year }}</p>
</span>
<span>
<p class="poster_genre-link">For age {{ $sfilm->films->age }} +</p>
</span>
</div>
</a>
</li>
</ol>
</div>
#endforeach
#else
<li class="list-group-item">{{ __('search_no_results') }}</li>
#endif
javascript ajax code:
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#search').keyup(function() {
var search = $('#search').val();
if (search == "") {
$("#memlist").html("");
$('#result').hide();
} else {
$.get("{{ URL::to('/search') }}", {
search: search
}, function(data) {
$('#memlist').empty().html(data);
$('#result').show();
})
}
});
});
Controller:
public function search(Request $request) : View
{
$search = $request->input('search');
$locales = app()->getLocale();
if ($locales == NULL) {
$sfilms = Local::where('title_en', 'like', "%$search%")
->orWhere('year', 'like', "$search%")->limit(4)->get();
} else {
$sfilms = Local::where('title' . '_' . $locales, 'like', "%$search%")
->orWhere('year', 'like', "$search%")->limit(4)->get();
}
return view('layouts.found')->with('sfilms', $sfilms);
}
This works correctly with searched results and I see them, but I don't fix to see exactly count of total results from request.
Collection use the count() method to return the total.
So you should be using it like this instead
{{ $sfilms->count() }}
Done
Just replace in controller ->limit(4)->get() to ->paginate(4). According to documentation
public function search(Request $request) : View
{
$search = $request->input('search');
$locales = app()->getLocale();
if ($locales == NULL) {
$sfilms = Local::where('title_en', 'like', "%$search%")
->orWhere('year', 'like', "$search%")->paginate(4);
} else {
$sfilms = Local::where('title' . '_' . $locales, 'like', "%$search%")
->orWhere('year', 'like', "$search%")->paginate(4);
}
return view('layouts.found', ['sfilms'=>$sfilms]);
}

Angular5 with HTML5 Drag and Drop

I try to use HTML5 Drag and Drop inside an Angular5 Component.
Where do I have to place my function in order to get it to work?
HTML example:
<div class="itemBox">
<div *ngFor="let count of this.modul.getSemesterCollums(input.maxKlausur)" id="{{ count }}" class="semesterBox" ondrop="drop(event)" ondragover="allowDrop(event)">
<a *ngFor="let item of this.modul.getArray(); let i = index">
<div *ngIf="item.getIDSemesterInt(input.maxKlausur, this.i) == (count + 1)" id="{{ item.getName() }}" class="item" draggable="true" ondragstart="drag(event)">
<p>{{item.getName()}}</p>
<hr/>
<ul>
<li>Übung: {{item.getUebungen()}}</li>
<li>Klausur: {{item.getKlausur()}}</li>
<li>Semester: {{item.getSemester()}}</li>
<li>Bestanden: <i class="fa fa-times"></i></li>
</ul>
</div>
</a>
</div>
</div>
Javascript Example:
function allowDrop(ev) {
ev.preventDefault();
if (ev.target.getAttribute("draggable") == "true")
ev.dataTransfer.dropEffect = "none"; // dropping is not allowed
else
ev.dataTransfer.dropEffect = "all"; // drop it like it's hot
}
it won't find it inside the component.ts and it won't find it inside "" Tags in the component.html.
Thanks for your time :)
fixed it.
Inserted the function in the export class:
export class DropComponent {
allowDrop(ev) {
ev.preventDefault();
if (ev.target.getAttribute("draggable") == "true")
ev.dataTransfer.dropEffect = "none"; // dropping is not allowed
else
ev.dataTransfer.dropEffect = "all"; // drop it like it's hot
}
[.....]
}
And I edit the HTML as following:
<div class="itemBox">
<div *ngFor="let count of this.modul.getSemesterCollums(input.maxKlausur)" id="{{ count }}" class="semesterBox" (drop)="drop($event)" (dragover)="allowDrop($event)">
<a *ngFor="let item of this.modul.getArray(); let i = index">
<div *ngIf="item.getIDSemesterInt(input.maxKlausur, this.i) == (count + 1)" id="{{ item.getName() }}" class="item" draggable="true" (dragstart)="drag($event)">
<p>{{item.getName()}}</p>
<hr/>
<ul>
<li>Übung: {{item.getUebungen()}}</li>
<li>Klausur: {{item.getKlausur()}}</li>
<li>Semester: {{item.getSemester()}}</li>
<li>Bestanden: <i class="fa fa-times"></i></li>
</ul>
</div>
</a>
</div>
</div>
And it works like a charm :)

Display data when click on button with Meteor

I have one button, when I click I want to display data only if the value of the checkbox is true, If it false, it's display when DOM is created
But I can't please look my code.
Template.students.helpers({
all_students: () => {
return students.find();
}
});
Template.body.onCreated(() => {
Meteor.subscribe('students');
});
Template.students.events({
'submit .insert': (e) => {
e.preventDefault();
students.insert({
name: e.target[0].value,
age: e.target[1].value,
check: false
});
this._checkValue(e);
},
'click .is-delete': (e) => {
students.remove(e.currentTarget.id);
},
'click .check-checkbox': (e) => {
students.update(e.currentTarget.id, {
$set: {
check: !this.check
}
})
},
'click .all': () => {
// HERE
}
})
<template name="students">
<div class="content menu">
<ul>
<button class="ui button all">All list</button> <!-- THIS BUTTON -->
{{#each all_students}}
<li class="content-list" id="{{ _id }}">
<div class="name">{{ name }}</div>
<div class="age">{{ age }} ans</div>
<span id="{{ _id }}" class="delete is-delete"></span>
<div class="ui checkbox">
<input id="{{ _id }}" class="check-checkbox" type="checkbox" name="check">
</div>
</li>
{{/each}}
</ul>
</div>
</template>
Inside of my event handler click .all if I try to return students.find() it doesn't work.
The easiest way is to use a ReactiveVar to flag if the list should show like so:
Add the ReactiveVar to your template instance
Template.students.onCreated(() => {
this.showAllStudents = new ReactiveVar(false);
this.subscribe('students');
});
Then expose it with a helper:
Template.students.helpers({
showStudents() {
Template.instance().showAllStudents.get();
},
all_students() {
students.find();
};
});
In your template, test for the flag
<template name="students">
<div class="content menu">
<ul>
<button class="ui button all">All list</button> <!-- THIS BUTTON -->
{{#if showStudents}}
{{#each all_students}}
<li class="content-list" id="{{ _id }}">
<div class="name">{{ name }}</div>
<div class="age">{{ age }} ans</div>
<span id="{{ _id }}" class="delete is-delete"></span>
<div class="ui checkbox">
<input id="{{ _id }}" class="check-checkbox" type="checkbox" name="check">
</div>
</li>
{{/each}}
{{/if}}
</ul>
</div>
</template>
And add the event handler which just switches the state (ie. set opposite of current state):
Template.students.events({
'click .all': (event, instance) => {
instance.showAllStudents.set(!instance.showAllStudents.get());
}
})
If you haven't already got it, run meteor add reactive-var to get the package.
And if you're using imports, use import { ReactiveVar } from 'meteor/reactive-var'; to import it.

Use NG-CLICK to change class on a clicked element

I am creating dynamic tabs using ajax data loaded via the WordPress REST-API. Everything is working, but I need to add a class to the active tab in order to use CSS transforms on it.
I would appreciate any suggestions. I know how to use ng-class when clicking one element affects another, but not when it affects the clicked element. It's also worth noting I am using the 'as' syntax for the ng-controller.
JAVASCRIPT:
var homeApp = angular.module('homeCharacters', ['ngSanitize']);
homeApp.controller('characters', function($scope, $http) {
$scope.myData = {
tab: 0
}; //set default tab
$http.get("http://bigbluecomics.dev/wp-json/posts?type=character").then(function(response) {
$scope.myData.data = response.data;
});
});
homeApp.filter('toTrusted', ['$sce',
function($sce) {
return function(text) {
return $sce.trustAsHtml(text);
};
}
]);
HTML:
<div class="more_comics_mobile">More Comics <img src="./images/white-arrow.png" />
</div>
<section class="characters" ng-app="homeCharacters" ng-controller="characters as myData">
<div class="char_copy" ng-repeat="item in myData.data" ng-bind-html="item.content | toTrusted" ng-show="myData.tab === item.menu_order">
{{ item.content }}
</div>
<div class="char_tabs">
<nav>
<ul ng-init="myData.tab = 0" ng-model='clicked'>
<li class="tab" ng-repeat="item in myData.data">
<a href ng-click="myData.tab = item.menu_order">
<img src="{{ item.featured_image.source }}" />
<h3>{{ item.title }}</h3>
</a>
</li>
</ul>
</nav>
</div>
</section>
I am trying to add the class to the li element. I appreciate any help!
You can use ng-class like
<li class="tab" ng-repeat="item in myData.data" ng-class="{'active' : item.menu_order == myData.tab}"></li>
For more options you can visit
https://docs.angularjs.org/api/ng/directive/ngClass
<div class="more_comics_mobile">More Comics <img src="./images/white-arrow.png" />
</div>
<section class="characters" ng-app="homeCharacters" ng-controller="characters as myData">
<div class="char_copy" ng-repeat="item in myData.data" ng-bind-html="item.content | toTrusted" ng-show="myData.tab === item.menu_order">
{{ item.content }}
</div>
<div class="char_tabs">
<nav>
<ul ng-init="myData.tab = 0" ng-model='clicked'>
<li class="tab" ng-click="activate($index)" ng-repeat="item in myData.data">
<a href ng-click="myData.tab = item.menu_order">
<img src="{{ item.featured_image.source }}" />
<h3>{{ item.title }}</h3>
</a>
</li>
</ul>
</nav>
</div>
</section>
in your js
$scope.activate = function(index){
document.getElementsByClassName.setAttribute("class","tab");
document.getElementsByClassName[index].setAttribute("class","tab active");
}

Angular JS ng-repeat

Working DEMO with Single List
Edit : Trying to Add Code Snippet IN JSON to Display in Front END as attached in the image.
can you please advice can we add ?
http://i.stack.imgur.com/Y2LOs.png
i have a list of data that has to be displayed in Listing, as of now i only have one object and only one li can add
can we render object in side a object just like this, i tried there is error.
"list":{
{"object":"1"},
{"object":"2"},
{"object":"3"},
{"object":"4"},
{"object":"5"}
}
JSON :
[
{
"title" : "JavaScript ?",
"description" : "Hey, here are some of the merits of javascript",
"list" : "JavaScript is very easy to implement. All you need to do is put your code in the HTML document and tell the browser that it is JavaScript.",
"uploadedDate" : "April 12 2015",
"tags" : "javascript, webdevelopment"
}
]
JS :
var app = angular.module("jsBlogApp", []);
//Menu
app.service("headerMenu", function($http, $q) {
var deferred = $q.defer();
$http.get('json/headerMenu.json').then(function(data){
deferred.resolve(data);
});
this.getMenuItems = function (){
return deferred.promise;
}
})
.controller("headerMenuCtrl", function($scope, headerMenu){
var promise = headerMenu.getMenuItems();
promise.then(function(data){
$scope.headerMenuItems = data.data;
console.log($scope.headerMenuItems);
})
})
// Secondary Menu
app.service("secondaryHeaderMenu", function($http, $q) {
var deferred = $q.defer();
$http.get('json/secondaryHeaderMenu.json').then(function(data){
deferred.resolve(data);
});
this.getSecondaryMenuItems = function (){
return deferred.promise;
}
})
.controller("SecondaryheaderMenuCtrl", function($scope, secondaryHeaderMenu){
var promise = secondaryHeaderMenu.getSecondaryMenuItems();
promise.then(function(data){
$scope.SecondaryMenuItems = data.data;
console.log($scope.SecondaryMenuItems);
})
})
app.service("jsBlogService", function($http, $q) {
var deferred = $q.defer();
$http.get('json/data.json').then(function(data){
deferred.resolve(data);
});
this.getPlayers = function (){
return deferred.promise;
}
})
.controller("jsBlogCtrl", function($scope, jsBlogService){
var promise = jsBlogService.getPlayers();
promise.then(function(data){
$scope.items = data.data;
console.log($scope.items);
})
})
HTML :
{{menu.title}}
<div class="second__header">
<div class="second__header__wrap clearfix">
<div class="js__logo__wrap">
<h1 class="js__logo">JS Developer</h1>
<div class="js__logo__subtitle">~ codeJS </div>
</div>
<div class="c2f__nav__wrap" data-ng-controller="SecondaryheaderMenuCtrl">
<ul class="c2f__nav">
<li data-ng-repeat="menu in SecondaryMenuItems">
{{menu.title}}
</li>
</ul>
</div>
</div>
</div>
</header>
<section class="c2f__content clearfix">
<div class="c2f__cont_left">
<!--content starts-->
<div class="content__wrap" data-ng-controller="jsBlogCtrl">
<div data-ng-repeat="item in items">
<h2 class="title__head"> {{ item.title }}</h2>
<p class="desc__head">{{ item.description }}</p>
<p>Listing
<ul class="data__lisitng">
<li>
<span>{{ item.list }}</span>
</li>
</ul>
</p>
<div class="code"></div>
<span class="content__added__date">
{{ item.uploadedDate }}
</span>
<span class="content__tags">
<span class="tags__links__title">Tags - </span>
<span class="tags__links__desc">{{ item.tags }}</span>
</span>
</div>
</div>
</div>
</section>
<footer>
</footer>
</div>
I finally get what you were trying:
Here is a working plunkr: https://plnkr.co/edit/8TLDTV0OtE10hITr9Vf9?p=preview
JSON
[
{
"title" : "JavaScript ?",
"description" : "Hey, here are some of the merits of javascript",
"list" : [
{
"subtitle":"subtitle1",
"message":"message1"
},
{
"subtitle":"subtitle2",
"message":"message2"
}
] ,
"uploadedDate" : "April 12 2015",
"tags" : "javascript, webdevelopment"
}
]
HTML
<div class="content__wrap" data-ng-controller="jsBlogCtrl">
<div data-ng-repeat="item in items">
<h2 class="title__head"> {{ item.title }}</h2>
<p class="desc__head">{{ item.description }}</p>
<p>Listing
</p>
<ul class="data__lisitng">
<li ng-repeat="message in item.list">
<span>{{ message.message }}</span>
</li>
</ul>
<p></p>
<div class="code"></div>
<span class="content__added__date">
{{ item.uploadedDate }}
</span>
<span class="content__tags">
<span class="tags__links__title">Tags - </span>
<span class="tags__links__desc">{{ item.tags }}</span>
</span>
</div>
</div>
At least the list should be like this instead:
"list":[
{"object":"1"},
{"object":"2"},
{"object":"3"},
{"object":"4"},
{"object":"5"}
];
I would prefer something like:
$scope.list = [
{"object":"1"},
{"object":"2"},
{"object":"3"},
{"object":"4"},
{"object":"5"}
];
use '[' instead of '{'
[
{"object":"1"},
{"object":"2"},
{"object":"3"},
{"object":"4"},
{"object":"5"}
]
"list":{
{"object":"1"},
{"object":"2"},
{"object":"3"},
{"object":"4"},
{"object":"5"}
}
is not valid. Please use a valid object/array for ng-repeat

Categories