Pass parametar througth function and show it - angularjs

I have problem with passing params with one function to another.
I am passing params like this:
<div ng-click="changeView('distance')">EXPAND
</div>
And in my controller
$scope.changeView = function (params) {
$scope.currentView = params;
};
I have more pages with more option. In my option I am selecting team, but I want to show depending on my changeView.
This is my select for teams
<select style="width: 100%;" ng-model="selectedTeam" ng-options="x.team_name for x in teams" ng-change="changeLocation(selectedTeam.team_id);"
</select>
And this is in my controller for changeLocation
$scope.changeLocation = function (teamId) {
$scope.showPlayer = true;
if ($scope.currentView == undefined) {
$state.go('activity-statistic.activity-statistic-team-heart', { teamId: teamId }, { reload: false });
}
else {
$state.go('activity-statistic.activity-statistic-team-' + $scope.currentView + '', { teamId: teamId }, { reload: false });
}
};
When I want to change location, my $scope.curentView is undefined always.
Any idea what I'm doing wrong?

Its looks like that your $scope.changeView and $scope.changeLocation both belong to different controllers $scope has its scope only in the current controller that why its showing undef
You can use $rootscope instead for global scope something like
$scope.changeView = function (params) {
$rootscope.currentView = params;
};
then change
if ($scope.currentView == undefined)
to
if ($rootscope.currentView == undefined)

Related

md-select component loses ng-selected value

I work with Angular 1.5.4 & material 1.0.6. Everything of the following example is working fine if I use chrome. But if I use safari no value is preselected.
The template of the component looks like
<md-select ng-model="$ctrl.selectedFruit">
<md-option ng-repeat="fruit in $ctrl.fruits" ng-value="fruit" required
ng-selected="$first" >
{{fruit.name}} {{fruit.weight}}
</md-option>
</md-select>
the component looks like
.component('applicantAccount', {
// #ngInject
bindings: {
selectedFruit: "="
},
controller: function (accountService) {
var ctrl = this;
fruitService.initFruitBefore(function () {
ctrl.fruits= fruitService.getFruits();
});
},
templateUrl: 'views/templates/selectFruitTemplate.html'
});
fruitService:
var fruits = [];
var initFruits = function () {
return $http.get(configuration.apiUrl + "fruits")
.then(function success(response) {
fruits = response.data || []
return response;
})
};
var getFruits = function () {
var filterEx = {type: "fresh"};
return $filter('filter')(fruits , filterEx);
};
var initFruitBefore = function (callback) {
if (!areFruitsAvailable()) {
initFruits().then(callback);
}
else{
callback();
}
};
var areFruitsAvailable = function () {
return typeof fruits[0] !== 'undefined'
};
var getFreshFruit = function () {
var filterEx = {type: "fresh"};
var filtered = $filter('filter')(fruits, filterEx);
return filtered[0] || null;
};
controller:
fruitService.initFruitBefore(function () {
ctrl.selectedFruit = accountService.getFreshFruit();
ctrl.fruits = accountService.getFruits();
});
The odd thing(only safari) is, that ctrl.fruits gets initialized before selectedFruit is initialized (outside of the component). If this happens the value was shown for a short term.
Has anyone an idea whats going on? Why behaves the safari different?
Thank you & sorry for my bad english
The Solution
I added ng-model-options={trackBy:'$value.id'}.
Angular Material:
To determine whether something is selected, ngModelController is looking at whether $scope.selectedUser == (any user in $scope.users);;
Javascript's == operator does not check for deep equality (ie. that all properties on the object are the same), but instead whether the objects are the same object in memory. In this case, we have two instances of identical objects, but they exist in memory as unique entities. Because of this, the select will have no value populated for a selected user.
For futher description look at https://material.angularjs.org/latest/api/directive/mdSelect

Change in data made by $http inside a factory is not reflected to the DOM

I'm trying to create a dynamic form based on an object.
For example: I'd like that generated select boxes will contain options if given, otherwise a factory will fetch them using ajax, something like this:
Markup:
<select ng-repeat="select in selects"
ng-init="options = refactor.options(select)"
ng-options="option in options">
</select>
Controller:
myApp.controller('MyCtrl', function($scope, refactor) {
$scope.refactor = refactor;
$scope.selects = [
{ text: "Country", value="chosen.country", options=["France", "England"] },
{ text: "Gender", value="chosen.gender", options="/gender" }
]
});
Factory:
myApp.factory('refactor', function($scope, $http) {
return {
options: function(select) {
if(typeof(select.options) === 'object') { return select.options };
// otherwise assume select.options is
// a path to fetch options by ajax:
$http.get(select.options).success(function(data) {
select.options = data; // data == ['male', 'female']
});
return []; // placeholder until promise is fulfilled
}
}
})
The data ( $scope.selects ) gets updated as expected, yet the DOM is not, which probably means refactor.options() is not being invoked again in response to the change. I tried to force an update by passing the scope object to the factory and invoke $apply on it, but it doesn't work.
What am I missing?
You need to use ng-init="data = refactor.options(select)" so after getting data from ajax data would be filled up with options then you could use ng-options as instead of ng-options="option in data.options".
Markup
<select ng-repeat="select in selects"
ng-init="data = refactor.options(select)"
ng-options="option in data.options">
</select>
You should try this
myApp.factory('refactor', function($scope, $http) {
return {
options: function(select) {
var menuItems={
options:[]
}
if(typeof(select.options) === 'object'){
menuItems.options=select.options
};
// otherwise assume select.options is
// a path to fetch options by ajax:
$http.get(select.options).success(function(data) {
select.options = data;
menuItems.options=data;// data == ['male', 'female']
});
return menuItems; // placeholder until promise is fulfilled
}
}
});
Then inside your view it should go like this
<select ng-repeat="select in selects"
ng-init="menuItems= refactor.options(select)"
ng-options="option in menuItems.options">
</select>

Changing expression provided to ngShow attribute using controller

I am using ng-show and ng-hide to display/hide content. I would like to change the showme status from true to false within the controller. But when I use the code below, it doesn't work. I'm using the Controller As syntax. Any suggestions on how to get this working right?
HTML:
<h1 ng-show="showme">Confirm Order</h1>
<h4 ng-hide="showme">Contact Information</h4>
Javascript:
.controller('ContactFormCtrl',
function ($http, serviceF, $scope) {
var contactForm = this;
$scope.$watch(serviceF.get, function(valid)
{
if (valid === 'yes') {
contactForm.showme=true;
}
else
{
contactForm.showme=false;
}
});
});
Service:
.service('serviceF', function() {
var valid = 'true';
return {
get: function () {
return valid;
},
set: function (value) {
valid = value;
}
};
UI Router:
.state('payment', {
url: '/payment',
views: {
// . . .
'top': {
templateUrl: 'views/clientinfo.html',
controller: 'ContactFormCtrl as contactForm'
// . . .
}
})
I'm not sure what you're trying to do, but the Controller As syntax goes this way in HTML:
<div ng-controller="ContactFormCtrl as contactForm">
<h1 ng-show="contactForm.showme">Confirm Order</h1>
<h1 ng-show="contactForm.showme">Confirm Order</h1>
</div>
Note the 'as contactForm' thingy passed in the ng-controller directive
Now you know that showme is actually a property of contactForm which is essentially an "alias" of the ContactFormCtrl controller
From there, whenever the showme property changes in the controller, the view will behave accordingly.
// In your controller
var contactForm = this; // aliasing this
contactForm.showme = true; //or false
UPDATE:
Since you're using ui-router, you should be good without ng-controller in your view. I'm noticing you are not passing $scope to your controller, that could be a reason why $scope.$watch isn't working, thus not updating the view.
.controller('ContactFormCtrl', function ($scope, $http, serviceF) {
var contactForm = this;
$scope.$watch(serviceF.get, function(valid) {
if (valid === 'yes') {
contactForm.showme = true;
}else{
contactForm.showme = false;
}
});
});

Angular Factory data isn't shared correctly

I'm trying to share some data from the controller in the current view to my navigation bar. but the data is shared wrong, or not synced correctly.
this is my factory:
myApp.factory('HeaderData', function () {
var data = {
Visible: true,
PageTitle: ''
};
return {
getVisible: function () {
return data.Visible;
},
setVisible: function (visible) {
data.Visible = visible;
console.log("HeaderData: " +visible);
},
getPageTitle: function () {
return data.PageTitle;
},
setPageTitle: function (title) {
data.PageTitle = title;
}
};
});
then in my controllers I'm doing the following:
myApp.controller('homeCtrl',function ($scope, HeaderData) {
HeaderData.setVisible(false);
console.log("HomeCtrl: " + HeaderData.getVisible());
});
in the Nav controller I read the data in like following:
myApp.controller('navCtrl', function ($scope, HeaderData) {
console.log("NavCtrl: " +HeaderData.getVisible());
$scope.showHeader = HeaderData.getVisible();
$scope.pageTitle = HeaderData.getPageTitle();
});
the following output is logged:
NavCtrl: true
HeaderData: false
HomeCtrl: false
So my NavContrl is loaded before my Data is set, and this is logical because it's like this in the HTML:
<div ng-controller="navCtrl">
<ng-include ng-show="showHeader" src="'../partials/common/header.html'"></ng-include>
</div>
<div ng-view></div>
So how can I make it work that my navCtrl updates the data correctly, and in this example hide the header when the $scope.showHeader is set to false?
Instead of assigning a primitive to $scope, assign an object to scope so that you can bind by reference. By binding by reference, you ensure that scope properties resolve to the same reference.
When you bind to a primitive (string, int, etc), it creates a copy of the original value on scope as soon as it is assigned. Now you have multiple copies of the variable on different scopes, and they all behave independently of each other.
myApp.factory('HeaderData', function() {
var data = {
Visible: true,
PageTitle: ''
};
return {
...
getData = function() {
return data;
}
};
});
And assign the model to scope:
myApp.controller('navCtrl', function($scope, HeaderData) {
$scope.data = HeaderData.getData();
});
And in your HTML:
<div ng-controller="navCtrl">
<div ng-show="data.Visible">HEADER</div>
</div>

Removing Items From Favourite List

I am working on angular js on single page application in mvc arcitecture i have a list of favourites i want to delete on my click event
Html For Angular
<div class="favourite" ng-repeat="favourite in category.favourites | orderBy:'title'">
<a class="title" ng-href="{{favourite.url}}" ng-bind-html="favourite.title | mlStripHtml"></a>
<div ng-if="profileFavourites.canDelete" class="remove" title="{{ 'TaBort' | mlLocalization }}" ng-click="profileFavourites.remove(favourite, $event,$index)"></div>
</div>
Angular Js
FavouriteService.getFavourites(profileId).then(
function (favourites) {
$scope.categories = []
_.forEach(favourites, function (fav) {
var category = _.find($scope.categories, function (cat) {
$scope
return cat.id == fav.type
})
if (category) {
category.favourites.push(fav)
return
}
category = {
id: fav.type,
name: Language.getTypeName(fav.type, {
case: 'none'
}),
favourites: [fav]
}
$scope.categories.push(category)
})
$scope.isLoadingFavourites = false
})
$scope.remove = function (favourite, $event) {
$event.preventDefault()
$event.stopPropagation()
FavouriteService.removeFromFavourites(favourite.id).then(
function () {
alert("favourite")
var category = _.find($scope.categories, function (cat) {
return cat.id == favourite.type
})
if (category) return
_.remove(category.favourites, function (fav) {
return fav.id == favourite.id
})
if (!category.favourites.length) {
_.remove(scope.categories, function (cat) {
return cat.id == category.id
})
}
})
}
The above mention is my code for the removal of item from the list it works perfectly fine when i click on delete link it successfully delete the item but the onlu issue is it does not reflect the change till the page gets refrehed i m tryingh hard but could not resolve it as i m new to angular js any help will be appreciated
you are passing $index in remove method so you can use below code to remove favourite
$scope.remove = function (favourite, $event,index) {
$event.preventDefault()
$event.stopPropagation()
FavouriteService.removeFromFavourites(favourite.id).then(
function () {
alert("favourite")
$scope.category.favourites.splice(index,1);
})
it will refresh your list.

Resources