How to check whether an object is empty in a span? - arrays

I have some objects in my angularjs controller.
var app = angular.module("myApp", []);
app.controller("noteCtrl", function ($scope) {
$scope.draft = {};
$scope.notes = [];
$scope.note = {};
$scope.submit = function() {
$scope.notes.push($scope.note);
$scope.note = {};
};
$scope.save = function() {
if ($scope.button == "Save") {
$scope.draft = angular.copy($scope.note);
} else {
$scope.note = $scope.draft;
}
};
$scope.cancel = function() {
$scope.note = {};
}
});
I need to check whether the draft object is empty, and output the save successfully information.
<span data-ng-hide="draft == {}" style="color:green">Your note has been saved.</span>
I have also tried:
<span data-ng-hide="draft.length == -1" style="color:green">Your note has been saved.</span>
or
<span data-ng-hide="draft == ''" style="color:green">Your note has been saved.</span>
But all of them are failed.

Add function isEmptyObject in your controller:
var app = angular.module("myApp", []);
app.controller("noteCtrl", function ($scope) {
$scope.draft = {};
$scope.note = {};
$scope.notes = [];
$scope.save = function() {
if ($scope.button == "Save") {
$scope.draft = angular.copy($scope.note);
} else {
$scope.note = $scope.draft;
}
};
$scope.cancel = function() {
$scope.note = {};
}
$scope.isEmptyObject = function (obj) {
for (var i in obj) if (obj.hasOwnProperty(i)) return false;
return true;
};
});
Or you can use this function:
$scope.isEmptyObject = function (obj) {
return Object.keys(obj).length === 0;
}
HTML:
<span data-ng-hide="isEmptyObject(draft)" style="color:green">Your note has been saved.</span>

Please initialize null instead of empty object
$scope.draft = null;
And html should be
<span data-ng-hide="!draft" style="color:green">Your note has been saved.</span>

You can chek the condition inline in your span.
HTML:
<span data-ng-hide="Object.keys(draft).length === 0" style="color:green">Your note has been saved.</span>

Related

Scope from controller does not pass to directive

I have a html like this :
<div id="create-group" ng-controller="groupCreateController">
<div id="container">
<h1>Create group</h1>
<div class="row">
<div class="col-md-4"><input placeholder="Group Name.." ng-model="group.name"></div>
<div class="col-md-8">
<label>Group Description : </label>
<textarea ng-model="group.description"> </textarea>
</div>
</div>
<br/>
<div class="row">
<div class="col-sm-6">
<usermgr-permission-list group="group"></usermgr-permission-list>
<button type="button" class="btn btn-md btn-primary" ng-click="btnSave_click($event)">SAVE</button>
</div>
<div class="col-sm-6">
<usermgr-user-list group="group"></usermgr-user-list>
</div>
</div>
</div>
</div>
My controller is :
(function (module) {
'use strict';
module.controller('groupCreateController', function ($scope, $rootScope, $routeParams, $location, userGroupService, $mdDialog) {
$scope.group = [];
$scope.init = function () {
if ($routeParams.hasOwnProperty('id')) {
//edit mode
// $scope.trans.heading = 'Edit Release';
// $scope.trans.saveBtn = 'Save';
var id = parseInt($routeParams.id);
getUserGroup(id);
} else {
$scope.group[0].id = 0;
$scope.group[0].permissions = [];
$scope.assignedPermissions = [];
$scope.enrolledUsers = [];
$scope.group[0].users = [];
$scope.group[0].name = '';
$scope.group[0].description = '';
}
};
function getUserGroup(id) {
userGroupService.getbyid(id).then(function (info) {
if (info !== undefined && info.id === id) {
$scope.group[0].id = info.id;
$scope.group[0].name = info.name;
$scope.group[0].description = info.description;
console.log($scope.group);
// $rootScope.$broadcast('rCube-user-mgt-users-list', info.id);
// $rootScope.$broadcast('rCube-user-mgt-permissions-list', info.id);
}
else {
}
}).catch(function (exception) {
console.error(exception);
});
}
$scope.init();
});
})(angular.module('r-cube-user-mgt.user-group'));
I have two custom directives in the first block of code for user permissions and users. The group scope that i pass with the directive does not contain the values i put in the getUserGroup(id) function. The group name and group description shows up so the scope.group in the controller is filled, however thats not the case once i pass it to my directives. here is the directives code as well :
permissions list :
(function (module) {
'use strict';
module.directive('usermgrPermissionList', function () {
return {
restrict: 'E',
scope:{
group: '='
},
controller: function ($scope, permissionService) {
$scope.updatedPermissions=[];
console.log($scope.group); //it doesnt have the values from the controller ..
if (!$scope.group.hasOwnProperty('permissions')) {
$scope.group.permissions = [];
}
function getData() {
console.log("inside getDAta for permission list" + $scope.group.id;
permissionService.getPermissionsFiltered($scope.group.id).then(function (info) {
if (info && info.length > 0) {
console.log(info);
$scope.group.permissions = info.map(function (a, index, array) {
return {
id: a.id,
name: a.name,
description: a.description,
assigned: a.assigned
};
});
}
}).catch(function (exception) {
console.error(exception);
});
} //end of getData()
$scope.init = function () {
getData();
};
$scope.init();
},
templateUrl: 'r-cube-user-mgt/permission/list/list.tpl.html'
};
});
})(angular.module('r-cube-user-mgt.permission'));
can anyone help?
you cannot assign property to an array like this $scope.group.id = 0;
either make $scope.group object
$scope.group = {};
or add properties to an index
$scope.group = [];
$scope.init = function () {
if ($routeParams.hasOwnProperty('id')) {
//edit mode
// $scope.trans.heading = 'Edit Release';
// $scope.trans.saveBtn = 'Save';
var id = parseInt($routeParams.id);
getUserGroup(id);
} else {
$scope.group[0].id = 0;
$scope.group[0].permissions = [];
$scope.assignedPermissions = [];
$scope.enrolledUsers = [];
$scope.group[0].users = [];
$scope.group[0].name = '';
$scope.group[0].description = '';
}
};
So I solved the issue by adding broadcast to send the id when the directive loads. This worked!
in the Group controller i add broadcast and send the group.id
function getUserGroup(id) {
userGroupService.getbyid(id).then(function (info) {
if (info !== undefined && info.id === id) {
$scope.group.id = info.id;
$scope.group.name = info.name;
$scope.group.description = info.description;
console.log($scope.group);
$rootScope.$broadcast(rCubeTopics.userMgtPermissionLoadData, $scope.group.id);
}
}).catch(function (exception) {
console.error(exception);
});
}
and in the permission directive get that broadcast :
$scope.$on(rCubeTopics.userMgtPermissionLoadData, function (event, id) {
console.log($scope.group.id);
getData();
});

Change selected value in md-autocomplete in angular material

I using md-autocomplete in my page, Now I need to edit a record, how to change selected value in md-autocomplete programmatically?
This is angular code:
app.controller('DemoCtrl', DemoCtrl);
function DemoCtrl($timeout, $q, $log) {
var self = this;
self.simulateQuery = false;
self.isDisabled = false;
self.states = loadAll();
self.querySearch = querySearch;
function querySearch(query) {
var results = query ? self.states.filter(createFilterFor(query)) : self.states,
deferred;
if (self.simulateQuery) {
deferred = $q.defer();
$timeout(function () {
deferred.resolve(results);
}, Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(state) {
return (state.value.indexOf(lowercaseQuery) != -1);
};
}
function loadAll() {
return totlaTablaeau.map(function (repo) {
repo.value = repo.address.toLowerCase();
return repo;
});
}
};
Here's a CodePen using the online docs example. You just need to set the value of md-selected-item.
Markup
<md-autocomplete ... md-selected-item="ctrl.selectedItem" ...></md-autocomplete>
...
<md-button class="md-raised md-primary" ng-click="ctrl.selectArkansas()">Select Arkansas</md-button>
JS
self.selectArkansas = function() {
self.selectedItem = {
value: "Arkansas".toLowerCase(),
display: "Arkansas"
};
}
Your Html template looks like this.
<md-autocomplete
md-selected-item="model"
md-search-text="search_text"
md-items="item in searchResults()"
md-item-text="item.title"
md-min-length="3"
md-floating-label="Your Label"
placeholder="placeholder"
>
<md-item-template>
<span> {{item.title}},{{item.name}}</span>
</md-item-template>
<md-not-found>
No matches found.
</md-not-found>
</md-autocomplete>
Your controller code
class Controller {
constructor($service) {
this.$service = $service;
}
//we are init the varible hare.
$onInit() {
this.search_text = "";
//set by defaut value in you auto complete.
this.model = {id:'0000',title:'defalt',name:'Your Name'};
}
}
//function for get data list
// $service this is service function we can define in over services file and we can inject this way
searchResults() {
let { $service, search_text } = this;
return $service.search(search_text).then((data) =>data.list).catch(err =>{ });
}
//Responce data look like this
//[{id:'00h1',title:'test1',name:'harish verma'},
//{id:'00h2',title:'test1',name:'harish verma'},
//{id:'00h3',title:'test1',name:'harish verma'},
//{id:'00h4',title:'test1',name:'harish verma'}];
}
Controller.$inject = [
"Service"
];
export default Controller;
set by defaut value in you auto complete.
this.model = {id:'0000',title:'defalt',name:'Your Name'};

AngularJS UI Bootstrap dismiss() won´t work

Let me start by saying that I am very new to angular.
I have tried to setup a modal ui which works fine. But when I click the "cancel" button on the interface nothing happens.
This is my code:
(function () {
var domainName = 'TournamentCategory';
angular.module('tournamentCategories').controller("CategoriesController",
['$scope', '$modal', 'guidGenerator', 'eventBus', domainName + "Service",
'TournamentCategoryModelFactory',
function ($scope, $modal, guidGenerator, eventBus, domainService, modelFactory)
{$scope.openTournamentTree = function () {
var modalInstance = $modal.open({
templateUrl: 'TournamentTreeModal.html',
controller: 'TreeController',
size: 'wide-90',
resolve: {
}
});
modalInstance.result.then(function (selectedItem) {
//$scope.selected = selectedItem;
}, function () {
//$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.ok = function () {
modalInstance.close();
}
$scope.cancel = function () {
modalInstance.dismiss('cancel');
};
}]);
})();
The HTML:
<script type="text/ng-template" id="TournamentTreeModal.html">
<div class="modal-header">
</div>
<div class="modal-body">
<div class="include-tree" ng-include="'tournament-tree.html'"></div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">GEM</button>
<button ng-click="cancel()" class="btn btn-warning" type="button" data-dismiss="modal">LUK, uden at gemme</button>
</div>
This is my "treeController"
angular.module('tournamentTree').controller("TreeController", ['$scope', 'guidGenerator', function ($scope, guidGenerator) {
$scope.allMatches = [];
$scope.finalMatch = [createNewMatch()];
$scope.tierCount = 1;
$scope.previousMatchTier = 0;
$scope.deletePreviousMatches = function (parentMatch) {
for (var i in parentMatch.previousMatches) {
var previousMatch = parentMatch.previousMatches[i];
_.remove($scope.allMatches, function (match) { return match.id == previousMatch.id });
}
parentMatch.previousMatches = [];
}
$scope.addMatches = function (thisMatch) {
if (thisMatch && !thisMatch.previousMatches)
thisMatch.previousMatches = [];
if (thisMatch && thisMatch.previousMatches.length == 0) {
thisMatch.previousMatches.push(createNewMatch(thisMatch));
thisMatch.previousMatches.push(createNewMatch(thisMatch));
}
}
$scope.addMatchTier = function () {
for (var i in $scope.allMatches) {
var match = $scope.allMatches[i];
if (match.previousMatches.length == 0) {
$scope.addMatches(match);
}
}
$scope.tierCount++;
}
$scope.previousMatchTier = function () {
for (var i in $scope.allMatches) {
var previous;
if (previous.allMatches.length == i) {
previous = $scope.allMatches[i] - $scope.allMatches[i - 1];
}
}
}
$scope.removeMatchTier = function () {
//if (confirm('Er du sikker på, at du vil slette det yderste niveau af turneringstræet?')) {
var matchesToDelete = [];
for (var i in $scope.allMatches) {
var match = $scope.allMatches[i];
if (match.previousMatches.length == 0) {
matchesToDelete.push(match.nextMatch);
//$scope.deletePreviousMatches(match.nextMatch);
}
}
for (var i in matchesToDelete) {
$scope.deletePreviousMatches(matchesToDelete[i]);
}
$scope.tierCount--;
//}
}
$scope.hasPreviousMatches = function (match) {
return match && match.previousMatches && match.previousMatches.length > 0;
}
$scope.moveWinnerToNextMatch = function (match, winnerName) {
match.nextMatch.setPlayerName(match.id, winnerName);
}
function createNewMatch(nextMatch) {
var newMatch = {};
newMatch.tier = nextMatch && nextMatch.tier ? nextMatch.tier + 1 : 1;
newMatch.id = guidGenerator.newGuid();
newMatch.player1 = "";
newMatch.player2 = "";
newMatch.nextMatch = nextMatch;
newMatch.previousMatches = [];
newMatch.setPlayerName = function(matchId, playerName) {
for (var i in newMatch.previousMatches)
{
if (newMatch.previousMatches[i].id == matchId)
{
if (i == 0)
newMatch.player1 = playerName;
else
newMatch.player2 = playerName;
}
}
}
$scope.allMatches.push(newMatch);
return newMatch;
}
}]);
$dismiss is already available on modal scope so in template raplace cancel() with $dimiss() http://angular-ui.github.io/bootstrap/#/modal
That needs to go in your modals controller 'TreeController'
angular.module('tournamentCategories').controller('TreeController', function($scope, $modalInstance) {
$scope.ok = function () {
modalInstance.close();
}
$scope.cancel = function () {
modalInstance.dismiss('cancel');
};
});
I have an example in this plunker

Creating jasmine unit test for angular directive

The below directive checks/loads the template with value "pass, fail, required".
The conditions are
if(parent value == required){
1. if the value is true --> $scope.msg = "fail" --> loads the template with {{msg}} value
2. if the value is false --> $scope.msg = "pass" --> loads the template with {{msg}} value
}
In detail,
loading Template: [showerror.html]
<div>{{msg}}</div>
Directive Call:
<div show-error="obj"></div>
(obj contains as obj.error and obj.required )
Directive:
angular.module("dsf").directive('showError', [
function () {
'use strict';
return {
scope: {
obj: '=showError'
},
link: function ($scope) {
$scope.showError = {};
$scope.msg = "";
function setTemplate(filename) {
$scope.showError.template = 'app/path/' + filename + '.html';
}
$scope.$watch(function () {
if ($scope.obj.required === true) {
if ($scope.obj.error === false) {
$scope.msg = "Pass";
} else if ($scope.obj.error === "required") {
$scope.msg = "Required";
} else if ($scope.obj.error === true) {
$scope.msg = "fail";
}
} else {
if ($scope.obj.error === true) {
$scope.msg = "fail";
} else if ($scope.obj.error === false) {
$scope.msg = "Pass";
}
}
setTemplate("showerror");
});
},
template: '<div ng-include="showError.template"></div>'
};
}
]);
As i am new to jasmine test, how can i write the test for this directive? any suggestions?
Ok. I have written the unit test for this directive. What is the wrong now?
describe('showError', function () {
'use strict';
var compile, $scope, element;
beforeEach(module('dsf'));
beforeEach(inject(function ($compile, $rootScope) {
element = angular.element('<div show-error="obj"></div>');
$scope = $rootScope.$new();
compile = function (obj) {
$scope.obj = obj;
$compile(element)($scope);
$scope.$digest();
};
}));
it('updates the element when obj validation changes', function () {
var obj;
obj = {};
$scope = compile(obj);
$scope.apply(function () {
obj.required = true;
obj.error = true;
});
expect($scope.obj.msg).toContain('fail');
$scope.apply(function () {
obj.required = true;
obj.error = false;
});
expect($scope.obj.msg).toContain('Pass');
$scope.apply(function () {
obj.required = true;
obj.error = "required";
});
expect($scope.obj.msg).toContain('Required');
$scope.apply(function () {
obj.required = false;
obj.error = true;
});
expect($scope.obj.msg).toContain('Pass');
$scope.apply(function () {
obj.required = false;
obj.error = false;
});
expect($scope.obj.msg).toContain('fail');
});
});
I am getting error:
undefined is not an object (evaluating $scopr.apply) error
The command you're looking for is $scope.$apply() not $scope.apply().

Why is my Factory not getting instantiated/injected?

Why is readingController not able to use the Romanize service? It always says Romanize is undefined inside the function. How can I get the service in scope?
var readingController = function (scope, Romanize){
scope.currentMaterial = scope.sections[scope.sectionNumber].tutorials[scope.tutorialNumber].material;
Romanize;
}
var app = angular.module('Tutorials', ['functions', 'tutorials']).controller('getAnswers', function ($scope, $element) {
$scope.sectionNumber = 0;
$scope.tutorialNumber = 0;
$scope.questionNumber = 0;
$scope.sections = sections;
$scope.loadFromMenu = function (sec, tut, first) {
if (tut === $scope.tutorialNumber && sec === $scope.sectionNumber && !first) {//if clicked on already playing tut
return;
}
if (tut !== undefined && sec !== undefined) {
$scope.tutorialNumber = tut;
$scope.sectionNumber = sec;
}
for (var x in sections) {
sections[x].active = "inactive";
for (var y in sections[x].tutorials){
sections[x].tutorials[y].active = "inactive";
}
}
var section = sections[$scope.sectionNumber];
section.active = "active";
section.tutorials[$scope.tutorialNumber].active = "active";
$scope.questionNumber = 0;
$scope.currentTutorialName = sections[$scope.sectionNumber].tutorials[$scope.tutorialNumber].name;
$scope.$apply();
if ($scope.sectionNumber === 0){
readingController($scope, app.Romanize);
}else if ($scope.sectionNumber === 1){
conjugationController($scope);
}
};
$scope.loadFromMenu(0,0, true);
var conjugationController = function (){
var loadNewVerbs = function (scope) {
scope.currentVerbSet = scope.sections[scope.sectionNumber].tutorials[scope.tutorialNumber].verbs;
if (scope.currentVerbSet === undefined) {
alert("Out of new questions");
return
}
scope.verbs = conjugate(scope.currentVerbSet[scope.questionNumber]);
scope.correct = scope.verbs.conjugations[0].text;
fisherYates(scope.verbs.conjugations);
scope.$apply();
};
loadNewVerbs($scope);
$scope.checkAnswer = function (answer) {
if($scope.sectionNumber === 0 && $scope.tutorialNumber === 0 && $("video")[0].currentTime < 160){
$scope.message = "Not yet!";
$(".message").show(300).delay(900).hide(300);
return;
}
answer.colorReveal = "reveal-color";
if (answer.text === $scope.correct) { //if correct skip to congratulations
$scope.questionNumber++;
setTimeout(function () {
loadNewVerbs($scope);
$scope.$apply();
}, 2000);
} else { //if incorrect skip to try again msg
if ($scope.sectionNumber === 0 && $scope.tutorialNumber === 0) {
start(160.5);
pause(163.8)
}
}
};
};
});
app.factory('Romanize', ['$http', function($http){
return{
get: function(){
$http.get(scope.sections[scope.sectionNumber].romanizeService).success(function(data) {
$scope.romanized = data;
});
}
};
}])
Update: based on comments/discussion below:
For a service to be instantiated, it has to be injected somewhere – not just anywhere – somewhere where Angular accepts injectables. Just inject it into your getAnswers controller – .controller('getAnswers', function ($scope, $element, Romanize) – then pass it to your "controller" function: readingController($scope, Romanize).
Since I don't think readingController is a real Angular controller, you can name the arguments whatever you want, so scope should be fine.
Original attempt at an answer:
Inject $scope not scope into your controller:
var readingController = function ($scope, Romanize){
Then I don't get any errors: Plunker.

Resources