Angular ng-show not correct when loading the page - javascript

I have the following checkboxes generated with AngularJS on my html page:
<div ng-controller="MirrorCheckboxController">
<div ng-repeat="setting in settings">
<input type="checkbox"
ng-attr-id="{{ setting.id }}"
ng-model="checkedElements[setting.id]"
ng-click="callSaveFunction(setting.id)">
<label ng-attr-for="{{ setting.id }}">
<span class="checkbox">{{setting.name}}</span>
</label>
</div>
</div>
<div ng-show="showEvents(checkedElements)" id="events">
...show something
</div>
If the last checkbox (Weather) is checked, the DIV with the ID "events" should be shown. This actually already works fine, I just have the problem that if I load the page and Weather is already true from the storage, the "DIV" events container doesn't show up. So I would need something to check that when loading the page and that works fine and doesn't get in the way of ng-show
My controller is:
exampleApp.controller('MirrorCheckboxController', ['$scope', function($scope) {
$scope.checkedElements = {};
$scope.settings = [{
name: 'Weather',
value: '',
id: 'mirror-1'
}, {
name: 'Date and Clock',
value: '',
id: 'mirror-2'
}, {
name: 'Traffic Situation',
value: '',
id: 'mirror-3'
}, {
name: 'Personal Calendar',
value: '',
id: 'mirror-4'
}];
// the method to display or hide the event container
$scope.showEvents = function(obj) {
return (obj['mirror-4']);
};
}]);
The storage works fine as well and the checkbox is also checked onload. Is there a possibility to use something else at the same time as ng-show just to catch that case when loading the page? I'm struggling with that for a while and tried some JQuery solutions, but nothing worked.
edit:
<script type="text/javascript">
// wait until bus service is available
window.name = 'NG_DEFER_BOOTSTRAP!';
window["Client"] = {
SID: "{{SID}}",
throwErrorOnBootFailure: true,
readyCallback: function () {
(function() {
$(document).ready(function() {
angular.resumeBootstrap([]);
});
})();
//load current checkbox states from the storage API while loading
loadMirror_WeatherEnabler();
}
};
</script>
<!-- Model API dependencies -->
<script type="text/javascript" src="/hcc/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="/bus/ModelAPICommunicationObject.js"></script>
<script type="text/javascript" src="/bus/ModelAPI.js"></script>
<script type="text/javascript" src="/bus/ModelAPIWebsocketClientFactory.js"></script>
<script type="text/javascript" src="/bus/bus-client-bootstrap.js"></script>

Related

How to manipulate the <title> of an AngularJS single page app?

I have a single-page AngularJS app.
The index.html file looks like this:
<html ng-app="myApp" ng-controller="MyCtrl as myctrl">
<head>
<link rel="stylesheet" href="my-style-sheet.css">
<title>{{myctrl.title}}</title>
</head>
<body>
<div class="container">
<ol>
<li><a ui-sref="stateA">StateA</a></li>
<li><a ui-sref="stateB">StateB</a></li>
</ol>
<div ui-view></div>
</div>
<script src="my-app.js"></script>
</body>
</html>
As the user clicks on the StateA or StateB links, the page displays the content of those pages in place of <div ui-view></div>. Terrific.
As the user clicks around, the displayed content changes. I need the title of the page to change too. Currently it gets the title from the controller MyCtrl like this: <title>{{myctrl.title}}</title>. But when the user clicks those links, those states each have their own controllers. So I cannot use <title>{{myctrl.title}}</title>.
How can I update the title when various states the user clicks on have different controllers?
You can attach some data to each state of your routes, like a value that can be used to set the title of the page.
.state('test', {
url: '/test',
templateUrl: '/templates/test.html',
data: {
title: 'test title'
}
})
Then write a directive to read the title. You can check to see if the required data is available on the state you are going to, and attach the whole thing to $stateChangeSuccess event.
function dynamicTitle($rootScope, $timeout) {
return {
link: function(scope, el) {
$rootScope.$on('$stateChangeSuccess', function(event, toState) {
var title = (toState.data && toState.data.title)
? toState.data.title
: 'Default title';
$timeout(function() {
el.text(title);
}, 0, false);
};);
}
};
}
angular.module('myApp').directive('dynamicTitle', dynamicTitle);
And attach it to your <title>
<title dynamic-title></title>
You can create an AngularJS factory, inject it, modify it by calling 'Title.setTitle()' from controllers
<html ng-app="app" ng-controller="Ctrl">
<head>
<title>{{ Title.title() }}</title>
app.factory('Title', function() {
var title = 'Hello';
return {
title: function() { return title; },
setTitle: function(newTitle) { title = newTitle }
};
});

Strange behaviour Angular driven select list

According to paper "How to set the initial selected value of a select element using Angular.JS ng-options & track by" by #Meligy which I used as a guidance to learn and solve my problem with implementing a select list (ng-options), I still encounter some strange collaterale behaviour.
Although the basic behaviour finally does what it should do, see Test Plunk, I still encounter strange behaviour on the selected item in that list. Not in my test plunk though, implemented in my developement site.
app.controller("TaskEditCtrl", function($scope) {
$scope.loadTaskEdit = loadTaskEdit;
function loadTaskEdit() {
taskLoadCompleted();
tasktypesLoadCompleted();
}
function taskLoadCompleted() {
$scope.tasks = [{
Id: 1,
Name: "Name",
Description: "Description",
TaskTypesId: 4
}
];
$scope.current_task_tasktypesid = $scope.tasks[0].TaskTypesId;
}
function tasktypesLoadCompleted() {
var tasktypes = [{ Id: 1, Name: "A" },
{ Id: 2, Name: "B" },
{ Id: 3, Name: "C" },
{ Id: 4, Name: "D" }];
$scope.available_tasktypes_models = tasktypes
}
$scope.submit = function(){
alert('Edited TaskViewModel (New Selected TaskTypeId) > Ready for Update: ' + $scope.tasks[0].TaskTypesId);
}
loadTaskEdit();
});
HTML
<form class="form-horizontal" role="form" novalidate angular-validator name="editTaskForm" angular-validator-submit="UpdateTask()">
<div ng-repeat="task in tasks">
<div>
<select ng-init="task.TaskTypes = {Id: task.TaskTypesId}"
ng-model="task.TaskTypes"
ng-change="task.TaskTypesId = task.TaskTypes.Id"
ng-options="option_tasttypes.Name for option_tasttypes in available_tasktypes_models track by option_tasttypes.Id">
</select>
</div>
</div>
<div class="">
<input type="submit" class="btn btn-primary" value="Update" ng-click="submit()" />
</div>
</form>
As said, see my test plunk which shows exactly what it supposed to do. Moreover, using 5 self-explaining images, I do hope to make my troulbe bit clearer what's the problem.
I'm a bit lost to figure out what's so troublesome. My 'water' is telling me something wrong or missing in css. Did have anybody out their ever have face comparable? What could cause me this trouble? Does have anybody out there have a clue?
Thanks in advance
[1
[]2
[]3
[]4
Apparently I'm a rookie on css. Any suggestion is welcome!
CSS
#region "style sheets"
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/css/site.css",
"~/content/css/bootstrap.css",
"~/content/css/bootstrap-theme.css",
"~/Content/css/font-awesome.css",
"~/Content/css/morris.css",
"~/Content/css/toastr.css",
"~/Content/css/jquery.fancybox.css",
"~/Content/css/loading-bar.css"));
#endregion "style sheets"
The key with the dropdown is to set the model to the object that was selected. I updated your code to behave the way that I believe you are asking for it to work.
The key differences are:
Set the ng-model of the dropdown to the selected object and not the id of the selected item. This will give you access to the full selected object and all it's properties.
Remove the ng-change binding - this is not necessary with 2 way data binding, and the value on the model (whatever is put in for ng-model) will automatically be updated.
In your HTML you were using properties that were never declared in the Controller $scope. I updated those to reflect the available variables that were in scope.
For more information on dropdowns please see the angular documentation. It's very useful for figuring these types of issues out - https://docs.angularjs.org/api/ng/directive/select
// Code goes here
var app = angular.module("myApp", []);
app.controller("TaskEditCtrl", function($scope) {
$scope.tasks = {};
$scope.current_task_tasktypesid = null;
$scope.selected_task_tasktype = null;
$scope.loadTaskEdit = loadTaskEdit;
function loadTaskEdit() {
taskLoadCompleted();
tasktypesLoadCompleted();
//EDIT: DEFAULT DROPDOWN SELECTED VALUE
$scope.selected_task_tasktype = $scope.available_tasktypes_models[2];
}
function taskLoadCompleted() {
$scope.tasks = [{
Id: 1,
Name: "Name",
Description: "Description",
TaskTypesId: 4
}
];
$scope.current_task_tasktypesid = $scope.tasks[0].TaskTypesId;
}
function tasktypesLoadCompleted() {
var tasktypes = [{ Id: 1, Name: "A" },
{ Id: 2, Name: "B" },
{ Id: 3, Name: "C" },
{ Id: 4, Name: "D" }];
$scope.available_tasktypes_models = tasktypes
}
$scope.submit = function(){
alert('submitted model: ' + $scope.selected_task_tasktype.Id);
}
loadTaskEdit();
});
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#*" data-semver="1.2.9" src="http://code.angularjs.org/1.2.9/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="myApp" ng-controller="TaskEditCtrl as edit">
<form class="form-horizontal" role="form" novalidate angular-validator name="editTaskForm" angular-validator-submit="UpdateTask()">
<div ng-repeat="task in available_tasktypes_models">
<div>Task (Id): {{task.Id}}</div>
<div>Name: {{task.Name}}</div>
<div>Descripton: {{task.Description}}</div>
</div>
<p>Current Task.TaskTypesId: {{selected_task_tasktype.Id}}</p>
<div>
<select
ng-model="selected_task_tasktype"
ng-options="option_tasttypes.Name for option_tasttypes in available_tasktypes_models track by option_tasttypes.Id">
</select>
</div>
<p>{{task.TaskTypes}}</p>
<p>{{selected_task_tasktypesid = task.TaskTypes}}</p>
<div class="">
<input type="submit" class="btn btn-primary" value="Update" ng-click="submit()" />
</div>
</form>
</body>
</html>
First, I need to state the implementation of #Meligy and the suggested input of 'dball' are correct. So, go with the flow of your choice.
Keep notice on your style sheets.
Finally, I figured out that the style property 'color' with the value 'white' of selector #editTaskWrapper as identifier of the parent
<div id="editTaskWrapper">
acted as the bad guy. One way or the other, if I comment 'color: white' in
#editTaskWrapper {
background-color: #337AB7;
/*color: white;*/
padding: 20px;
}
the selected item in the selectlist becomes visible. All other controls and values are not affected, only the selected list item.

Mixitup Angular.js directive (Angular.js watch doesn't work)

I need to integrate Angular.js with Mixitup, so I created directive like that
this is JSFiddle to my code: http://jsfiddle.net/zn7t9p6L/19/
var app = angular.module('app', []);
app.directive('mixitup',function(){
var linker = function(scope,element,attrs) {
scope.$watch('entities', function(){
console.log('reload');
element.mixItUp();
// how to tell mixitup to reload the data
});
console.log('starting')
};
return {
restrict:'A',
link: linker,
scope:{entities:'='}
}
})
app.controller('DrawingsController',
function DrawingsController($scope, $timeout) {
$scope.categories = ['Soft', 'Elements'];
$scope.drawings = [{
name: 'Water',
category: 'Elements',
value: '2'
}, {
name: 'Fire',
category: 'Elements',
value: '1'
}, {
name: 'Air',
category: 'Elements',
value: '4'
}, {
name: 'Coton',
category: 'Soft',
value: '3'
}, {
name: 'Whool',
category: 'Soft',
value: '5'
}];
$scope.add = function(){
$scope.drawings.push({name:'new soft',value:$scope.drawings.length,category:'Soft'})
console.dir($scope.drawings);
};
});
<script src="http://cdn.jsdelivr.net/jquery.mixitup/2.0.4/jquery.mixitup.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<div ng-controller="DrawingsController">
<div class="controls">
<label>Filter:</label>
<button class="filter" data-filter="all">All</button>
<button class="filter"
data-filter=".category-{{category}}"
ng-repeat="category in categories">{{category}}</button>
<label>Sort:</label>
<button class="sort" data-sort="myorder:asc">Asc</button>
<button class="sort" data-sort="myorder:desc">Desc</button>
<label>Add:</label>
<button data-ng-click="add()">Add</button>
</div>
<div mixitup='mixitup' class="container" entities='drawings'>
<div class="mix category-{{drawing.category}}"
data-myorder="{{drawing.value}}"
ng-repeat="drawing in drawings">Value : {{drawing.name}}</div>
</div>
</div>
My problem is when I try to add new element to the drawings array or even change the array, it doesn't reflect the changes immediately, you need to make some filters like sorting to reflect changes.
Also the watcher to "entities" work once at the beginning and doesn't work anymore when any changes happen later to the drawings array (it will print reload one time and will not print it anymore)
you can try it in jsfiddle
You can try to pass a 3rd argument to .$watch() as true.
http://docs.angularjs.org/api/ng.$rootScope.Scope
$watch(watchExpression, listener, objectEquality)
objectEquality(optional) – {boolean=} – Comparing the object for equality rather than for reference.
I found the answer after some digging
As #gayu said , the first step is to set the 3rd argument to be true this will fix the second problem of the watcher
To fix the first problem which is updating mixitup immediately , you will need to add this script to the watcher callback
element.mixItUp();
if(element.mixItUp('isLoaded')){
element.mixItUp('destroy', true);
element.mixItUp();
}
this the new JSfiddle : http://jsfiddle.net/zn7t9p6L/20/

Unable to get the selection when using angular-winjs ListView

I'm using angular-winjs to display a list. The HTML as well as the controller code is below. When I click the item, the selection is not set. As a result, the watch never gets called.
How can I get the selected item in the selection variable? My code looks similar to this issue, but have the problem still. I'm using the latest WinJS.
<div ng-app="myApp">
<div ng-controller="HomeTilesController">
<div>Selected count: {{selection.length}}, indexes: {{selection}}</div>
<win-list-view item-data-source="homeTiles" selection-mode="'single'" selection="selection">
<win-item-template>
<div class="tile">
<h5 class="win-h5">{{item.data.title}}</</h5>
</div>
</win-item-template>
<win-grid-layout></win-grid-layout>
</win-list-view>
</div>
</div>
HomeTilesController:
angular.module('myApp', ['winjs'])
.controller("HomeTilesController", ['$scope', function ($scope) {
$scope.homeTiles = [
{ title: 'Agents' },
{ title: 'Center' },
{ title: '' },
{ title: '' },
{ title: '' },
{ title: '' }];
$scope.selection = [1];
$scope.$watch('selection', function handleSelectionChange(newValue, oldValue) {
console.log('item selected');
})
}]);
The tiles are displayed correctly as below. You may notice that the Center tile (tile with the blue border) that has been selected as a result of setting the selection. But any other selection still shows the same value - selecting any other item wont set the selection.
The libraries are below:
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/js/bootstrap.js"></script>
<script src="~/lib/hammer.js/hammer.js"></script>
<script src="https://code.angularjs.org/tools/system.js"></script>
<script src="https://code.angularjs.org/tools/typescript.js"></script>
<script src="~/lib/angular/angular.min.js"></script>
<script src="https://code.angularjs.org/2.0.0-alpha.44/angular2.dev.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/winjs/4.4.0/css/ui-light.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/winjs/4.4.0/js/base.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/winjs/4.4.0/js/ui.js"></script>
<script src="https://cdn.rawgit.com/winjs/angular-winjs/master/js/angular-winjs.js"></script>
<script src="~/app/my-app.js"></script>
<link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
<script src="~/js/site.js" asp-append-version="true"></script>
You have to use selection-mode="'single'" tap-behavior="'directSelect'"
var myApp = angular.module("myApp", ['winjs']);
myApp.controller("myCtrl", ['$scope', myCtrl]);
function myCtrl($scope) {
$scope.selection = [];
$scope.homeTiles = [{
title: 'A1'
}, {
title: 'A2'
}, {
title: 'A3'
}, {
title: 'A4'
}, {
title: 'A5'
}, {
title: 'A6'
}];
}
HTML
<div ng-app="myApp">
<div ng-controller="myCtrl">
<div>Selected count: {{selection.length}}, indexes: {{selection.toString()}}</div>
<win-list-view item-data-source="homeTiles" selection="selection" selection-mode="'single'" tap-behavior="'directSelect'" class="listview win-selectionstylefilled">
<win-item-template>This list view item's rating is: {{item.data.rating}}</win-item-template>
<win-list-layout></win-list-layout>
</win-list-view>
</div>
</div>
Working code JSFiddle
WinJS ListView Interaction Examples ( Choose from dropdown )

Selection in first drop down populates data in second dropdown but only on first click, why?

I have 2 drop downs where selection of first drop down effects the data content of the second drop down.
The problem I have is this functionality is occurring only on first click instead it should happen every time.
Here is my jsFiddle with my working code and here is my code on jsbin(jsbin gives some error which I am unable to understand, help appreciated here too, #newbieTorture).
Thanks in Advance :)
App = Ember.Application.create();
App.Router.map(function() {
// put your routes here
});
App.ArticleAdapter= DS.FixtureAdapter.extend({});
App.Article =DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
shouldReloadAll:true,
comments: DS.hasMany('comment', {async : true})
//async tells compiler to load data from comment everytime this is rendered
});
App.Comment =DS.Model.extend({
text: DS.attr(),
shouldReloadAll:true,
article: DS.belongsTo('article', { async: true })
});
App.Article.FIXTURES=[
{
id:1,
title : 'Ember',
body:'Its a great technology but need lot of studying and practice',
comments:[1]
},{
id:2,
title : 'Angular',
body:'it takes less understanding but has more coding the ember',
comments:[2,3]
//this will be an aray coz it is has many relation
}
];
App.Comment.FIXTURES=[
{
id:1,
text : 'Yyyieee excited to learn ember',
aricle: 1
//its not an array coz it will be related to single object
},{
id:2,
text : 'I will start Angular once i have fininshed with ember',
article: 2
},{
id:3,
text : 'Angular can be interesting',
article: 2
}
];
App.CommentAdapter= DS.FixtureAdapter.extend();
App.IndexController = Ember.ArrayController.extend({
articleValue: null,
selected: null,
articleStore: Em.computed(function(){
console.log("data is : " + this.get('articleValue'));
console.log("data is : " + this.get('selected'));
return this.store.findAll("article");
}).property("selected"),
availableComment: Em.computed(function () {
var make = this.get('selected');
// the line below returns the id and not an object
console.log(make);
if (make === undefined || make === null)
return [];
return this.get('selected').get('comments');
}).property('articleValue'),
actions:{
callIndexController: function(){
var select= this.get("selected");
console.log("hi :" + select);
}
}
});
App.IndexRoute = Ember.Route.extend({
model: function() {
return [];
},
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ember Starter Kit</title>
</head>
<body>
<script type="text/x-handlebars">
<h2>Welcome to Ember.js</h2>
{{outlet}}
</script>
<script type="text/x-handlebars" id="index">
First drop down:
{{
view "select"
contentBinding=articleStore
optionLabelPath="content.title"
optionValuePath="content.id"
prompt="Pick a person:"
shouldReloadAll=true
selectionBinding=selected
valueBinding=articleValue
}}
<br>
<br>
Second drop down:
{{
view "select"
contentBinding=availableComment
optionLabelPath="content.text"
optionValuePath="content.id"
prompt="related task:"
shouldReloadAll=true
valueBinding=articleValue
}}
</script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://builds.emberjs.com/tags/v1.13.7/ember-template-compiler.js"></script>
<script src="http://builds.emberjs.com/tags/v1.13.7/ember.debug.js"></script>
<script src="http://builds.emberjs.com/tags/v1.13.7/ember-data.js"></script>
<script src="js/amit_dropdown.js"></script>
<!-- to activate the test runner, add the "?test" query string parameter -->
<script src="tests/runner.js"></script>
</body>
</html>

Categories