Convert click for static pages in AngularJS - javascript

I've setup this structure in my Ionic v1 app.
This is for contents and load more effect.
$scope.toggleItem= function(item) {
if ($scope.isItemShown(item)) {
$scope.shownItem = null;
} else {
$scope.shownItem = item;
}
};
$scope.isItemShown = function(item) {
return $scope.shownItem === item;
};
DEMO
But now I need another solution. I have a static content in the page so I should change this toggle method.
AFTER RESULT
I tried that but its not working. Whats the solution?
Thanks.

In your controller the members to reference are $scope.toggleGroup and $scope.isGroupShown, but you're calling $scope.toggleItem and $scope.isItemShown.
You can change the controller or view to match each other
Also, you are not using Ionic tags to make it work, you have the static content inside normal Divs!!
Finally, put parameters on the functions you're calling, the controller member function is expecting the "group" parameter:
<ion-item class="item-stable"
ng-click="toggleItem(100)"
ng-class="{active: isItemShown(100)}">
<i class="icon" ng-class="isItemShown(100) ? 'ion-minus' : 'ion-plus'"></i>
İş Sağlığı ve Güvenliği İçin Ne Gibi Önlemler Alabilirim?
</ion-item>
<ion-item class="item-accordion" ng-show="isItemShown(100)">
Tarım iş sağlığı ve güvenliği ...
</ion-item>
Note the "100" parameter in the calls to toggleItem(100) and isItemShown(100). It has to be a unique value per item, I have pass "100" just as a sample to demonstrate the idea
Working sample:
https://codepen.io/zameb/pen/Ljaymd?editors=1010
Good luck

Related

AngularJS - Get printed value from scope inside an attribute?

I'm currently working on an AngularJS project and I got stuck in this specific requirement.
We have a service that has all the data, DataFactoryService. Then, I have a controller called DataFactoryController that is making the magic and then plot it in the view.
<div ng-repeat = "list in collection">
{{list.name}}
...
</div>
Now, we have a requirement that pass multiple data into one element. I thought an "ng-repeat" would do, but we need to have it inside an element attribute.
The scenarios are:
At one of the pages, we have multiple lists with multiple data.
Each data has a unique code or ID that should be passed when we do an execution or button click.
There are instances that we're passing multiple data.
Something like this (if we have 3 items in a list or lists, so we're passing the 3 item codes of the list):
<a href = "#" class = "btn btn-primary" data-factory = "code1;code2;code3;">
Submit
</a>
<a href = "#" class = "btn btn-default" data-factory = "code1;code2;code3;">
Cancel
</a>
In the example above, code1,code2,code3 came from the list data. I tried several approach like "ng-repeat", "angular.each", array, "ng-model" but I got no success.
From all I've tried, I knew that "ng-model" is the most possible way to resolve my problem but I didn't know where to start. the code below didn't work though.
<span ng-model = "dataFactorySet.code">{{list.code}}</span>
{{dataFactorySet.code}}
The data is coming from the service, then being called in the controller, and being plot on the HTML page.
// Controller
$scope.list = dataFactoryService.getAllServices();
The data on the list are being loaded upon initialization and hoping to have the data tags initialized as well together with the list data.
The unique code(s) is/are part of the $scope.list.
// Sample JSON structure
[
{ // list level
name: 'My Docs',
debug: false,
contents: [ // list contents level
{
code: 'AHDV3128',
text: 'Directory of documents',
...
},
{
code: 'AHDV3155',
text: 'Directory of pictures',
...
},
],
....
},
{ // list level
name: 'My Features',
debug: false,
contents: [ // list contents level
{
code: 'AHGE5161',
text: 'Directory of documents',
...
},
{
code: 'AHGE1727',
text: 'Directory of pictures',
...
},
],
....
}
]
How can I do this?
PLUNKER -> http://plnkr.co/edit/Hb6bNi7hHbcFa9RtoaMU?p=preview
The solution for this particular problem could be writing 2 functions which will return the baseId and code with respect to the list in loop.
I would suggest to do it like below
Submit
Cancel
//inside your controller write the methods -
$scope.getDataFactory = function(list){
var factory = list.map( (a) => a.code );
factory = factory.join(";");
return factory;
}
$scope.getDataBase= function(list){
var base= list.map( (a) => a.baseId);
base= base.join(";");
return base;
}
Let me know if you see any issue in doing this. This will definitely solve your problem.
You don't really have to pass multiple data from UI if you are using Angular.
Two-way data binding is like blessing which is provided by Angular.
check your updated plunker here [http://plnkr.co/edit/mTzAIiMmiVzQfSkHGgoU?p=preview]1
What I have done here :
I assumed that there must be some unique id (I added Id in the list) in the list.
Pass that Id on click (ng-click) of Submit button.
You already have list in your controller and got the Id which item has been clicked, so you can easily fetch all the data of that Id from the list.
Hope this will help you... cheers.
So basing from Ashvin777's post. I came up with this solution in the Controller.
$scope.getFactoryData = function(list) {
var listData = list.contents;
listData = listData.map(function(i,j) {
return i.code;
});
return listData.join(';');
}

AngularJS Filter Best Practice

I have a filter I need to use two times (two pages/controllers), filtering on an object category. I can get this to work using this in each controller:
$scope.$on('category', function (event, arg) {
$scope.catSort = arg;
});
$scope.filterCat = function (item) {
return !$scope.catSort ?
item : (item.category == $scope.catSort);
};
The html i am filtering on:
<li dnd-draggable="item" ng-repeat="item in items| filter: filterCat">
</li>
I set the $scope.catSort which is what to filter on in a list of buttons the user can click:
<button class="btn btn-default" ng-click="$emit('category', 'all')">Show All</button>
<button class="btn btn-default" ng-click="$emit('category', 'Common')">Common</button>
The problem is, i have another html page with a different subset of categories that I need to filter on. Instead of just copying and pasting the $scope.filterCat function to filter again, I want to create a separate filter to inject into each controller (Thats best practice right?).
So what i have started is this for a separate filter:
angular.module("category-filter", [])
.filter('filterCat', function () {
return function (category, item) {
return !category ?
product : (item.category == $scope.catSort);
}
});
You can see i'm trying to get that category option as well. How do i reach into the scope and get the category? Should i use a service and on one of the button clicks set the category to filter on?
I'm still learning filters and what want to make sure its reusable and following best practices
Pass an object to the filter expression: filter:{category: '...', compareTo: '...'} and check it inside the filter function.

Update unrelated field when clicking Angular checkbox

I have a list of checkboxes for people, and I need to trigger an event that will display information about each person selected in another area of the view. I am getting the event to run in my controller and updating the array of staff information. However, the view is not updated with this information. I think this is probably some kind of scope issue, but cannot find anything that works. I have tried adding a $watch, my code seems to think that is already running. I have also tried adding a directive, but nothing in there seems to make this work any better. I am very, very new to Angular and do not know where to look for help on this.
My view includes the following:
<div data-ng-controller="staffController as staffCtrl" id="providerList" class="scrollDiv">
<fieldset>
<p data-ng-repeat="person in staffCtrl.persons">
<input type="checkbox" name="selectedPersons" value="{{ physician.StaffNumber }}" data-ng-model="person.isSelected"
data-ng-checked="isSelected(person.StaffNumber)" data-ng-change="staffCtrl.toggleSelection(person.StaffNumber)" />
{{ person.LastName }}, {{ person.FirstName }}<br />
</p>
</fieldset>
</div>
<div data-ng-controller="staffController as staffCtrl">
# of items: <span data-ng-bind="staffCtrl.infoList.length"></span>
<ul>
<li data-ng-repeat="info in staffCtrl.infoList">
<span data-ng-bind="info.staffInfoItem1"></span>
</li>
</ul>
</div>
My controller includes the following:
function getStaffInfo(staffId, date) {
staffService.getStaffInfoById(staffId)
.then(success)
.catch(failed);
function success(data) {
if (!self.infoList.length > 0) {
self.infoList = [];
}
var staffItems = { staffId: staffNumber, info: data };
self.infoList.push(staffItems);
}
function failed(err) {
self.errorMessage = err;
}
}
self.toggleSelection = function toggleSelection(staffId) {
var idx = self.selectedStaff.indexOf(staffId);
// is currently selected
if (idx >= 0) {
self.selectedStaff.splice(idx, 1);
removeInfoForStaff(staffId);
} else {
self.selectedStaff.push(staffId);
getStaffInfo(staffId);
}
};
Thanks in advance!!
In the code you posted, there are two main problems. One in the template, and one in the controller logic.
Your template is the following :
<div data-ng-controller="staffController as staffCtrl" id="providerList" class="scrollDiv">
<!-- ngRepeat where you select the persons -->
</div>
<div data-ng-controller="staffController as staffCtrl">
<!-- ngRepeat where you show persons info -->
</div>
Here, you declared twice the controller, therefore, you have two instances of it. When you select the persons, you are storing the info in the data structures of the first instance. But the part of the view that displays the infos is working with other instances of the data structures, that are undefined or empty. The controller should be declared on a parent element of the two divs.
The second mistake is the following :
if (!self.infoList.length > 0) {
self.infoList = [];
}
You probably meant :
if (!self.infoList) {
self.infoList = [];
}
which could be rewrited as :
self.infoList = self.infoList || [];

Change scope value in a different view

Ok, I have struggeled a lot with this thing for some days now and I'm stuck. Here is what I want; I want to change my scope value in a different view by clicking on a button. So if I'm in the index.html view and click on a button I want to change the value of a scope on the index2.html view, and then display that view. Here is an example of my code which is not working
index.html
<div ng-controller="IndexController">
<button class="button button-block button-assertive" ng-click="checkValues()" value="checkitems" >
check values
</button>
</div>
IndexController.js
angular
.module('legeApp')
.controller('IndexController', function($scope, supersonic, $filter) {
$scope.checkValues = function(){
$scope.Diagnose = 'test';
var view = new supersonic.ui.View("legeApp#index2.html");
var customAnimation = supersonic.ui.animate("flipHorizontalFromLeft");
supersonic.ui.layers.push(view, { animation: customAnimation });
};
});
index2.html
<div ng-controller="IndexController">
<div class="card">
<div class="item item-text-wrap">
Test<b>{{Diagnose}} </b>
</div>
</div>
</div>
I can give the value outside the checkValues method, but I want it to be two different values depending on the button you click. Please help
I tried the code suggested, but I received an error. What am I doing wrong?
I try the code below and receive this error "SyntaxError: Unexpected token ':' - undefined:undefined". I also did not quite understand how and why I want to target the new value with supersonic.ui.views.params.current in the new view. I want to get the new value in the new view, not in a controller?Do I need two different controllers? I just want to update my values in a html view without being in it.
supersonic.ui.layers.push:
( view: view,
options: { params: {$scope.Diagnose : 'test'}
animation: customAnimation
}) => Promise
According to the supersonic push docs, the params attribute is meant for passing parameters between views:
JSON string of optional parameters to be passed to the target View,
accessible via supersonic.ui.views.params.current.
Try calling
supersonic.ui.layers.push: (
view: view,
options: {
params: {valueToBeSentAccrossView: <Your Value>}
animation: customAnimation
}) => Promise
and then retrieving the value in the target view using supersonic.ui.views.params.current.

ng-model won't reflect changes?

I have built a simple shopping cart sample :
Those 3 lines are created via ng-repeat.
My goal :
I want the yellow part to become red when the relevant quantity ( red arrow) is more than 3.
So here is what I did : (http://jsbin.com/eXOgOpA/4/edit)
<div ng-repeat='item in items'>
<span ng-class='{isMoreThan3: IsMoreThan3()}'>{{item.title }}</span>
<input ng-model='item.quantity'>
...
</div>
Where IsMoreThan3 is a function which :
$scope.IsMoreThan3=function (){return $scope.item.quantity>3;};
Where
.isMoreThan3
{
color:red;
}
but it doesn't work.( calculations are ok , but the color is never red).
Question :
How can I fix my controller code to yield the right value for the model ?
In other words :
How can the controller , know the current item.quantity ?
nb
I know that I can put the logic into the markup But I don't want that. I want the controller to return a true/false value.
Try:
<span ng-class='{isMoreThan3: IsMoreThan3(item)}'>{{item.title }}</span>
JS:
$scope.IsMoreThan3=function (item){
return item.quantity>3;
};
The reason is ng-repeat will create its own scope, accessing $scope.item will not access the current item in the loop

Categories