AngularJS share data between nested components properly - javascript

I want to embed a nested component in a page.
(A page is actually a controller that can be reached via the $routeProvider service)
And I want to bring data from the main component to its child component and vice versa - in order to make all of the components in the page and the page itself talking with each other in a full data binding.
I success to send data from parent to child with specific bindings attributes, however, I am not getting a way to bring data from child to parent.
// lobby.js - the main page.
// we can reach this page via browser by the $routeProvider service
app.config(($routeProvider) => {
$routeProvider
.when("/", {
templateUrl : "screens/lobby/lobby.html"
})
});
app.controller("lobby", ($scope, datepickerService) => {
$scope.title = "Welcome to Lobby screen!";
$scope.order = {};
$scope.send = function() {
console.log($scope.order);
};
});
Lobby.html
<!-- This is lobby.html file -->
<!-- Which is the html template of the main page (lobby.js) -->
<link rel="stylesheet" href="screens/lobby/lobby.css">
<div class="lobby" ng-controller="lobby">
<date-picker type="default" model="startDate"></date-picker>
<date-picker type="default" model="endDate"></date-picker>
<button type="button" name="button" ng-click="send()">Send</button>
</div>
Now as you can see, in the lobby.html file I have a nested component which is <date-picker></date-picker>. From parent I pass to this child component two attributes: type and model.
Now lets see this component functionality:
// datepicker.js component (actually defined as a directive)
// Initializing a datepicker plugin from jQuery UI Lib.
app.directive("datePicker", (datepickerService) => {
return {
templateUrl: "/shared/datepicker/datepicker.html",
scope: {
model: "#",
type: "#",
},
link: function(scope, elements, attrs) {
$(function() {
setTimeout(function () {
$("." + scope.model).datepicker({
onSelect: function(value) {
value = datepickerService.correct(value);
$("." + scope.model).val(value);
console.log(value);
}
});
}, 200);
});
}
}
});
datepicker.html
<!-- datepicker.html the datepicker html template -->
<!-- Successfuly getting the datepicker to be loaded and work -->
<box ng-show="type=='default'">
<input type="text" class="{{model}}" readonly>
</box>
Now the problem: notice the:
// lobby.js
$scope.send = function() {
console.log($scope.order);
};
in the lobby.js file.
I need this to send the actual startDate and endDate to a remote server. However I cannot access this data! $scope.order remains blank.
I have tried using components instead of directives I have tried ng-include I have tried more lot of things that I wont bother you with, since I have spent on it more than 3 days.
How can I work with nested components so all of the data will be shared through each of them, including the main page in AngularJS in order to create a scaleable modern app?
Thanks.

For sending data from parent to child angular provides the $broadcast() method and for sending data from child to parent it provides the $emit() method.
More info:
http://www.binaryintellect.net/articles/5d8be0b6-e294-457e-82b0-ba7cc10cae0e.aspx

I think you have to reference your startDate and endDate within your order object. Right now it seems you save those directly on your $scope.
Try this to verify:
console.log($scope.order, $scope.startDate, $scope.endDate);
add "order." in front your objects within the model attribute.
<!-- This is lobby.html file -->
<!-- Which is the html template of the main page (lobby.js) -->
<link rel="stylesheet" href="screens/lobby/lobby.css">
<div class="lobby" ng-controller="lobby">
<date-picker type="default" model="order.startDate"></date-picker>
<date-picker type="default" model="order.endDate"></date-picker>
<button type="button" name="button" ng-click="send()">Send</button>
</div>
Also, you might also need to change the attribute definition of your component to use bidirectional binding. Use "=" instead of "#". # only represents a copy of the value when getting passed to your component and not saved back to the original object.
...
scope: {
model: "=",
type: "#",
},
...
Update:
Please find my working Plunker here https://embed.plnkr.co/2TVbcplXIJ01BMJFQbgv/

Related

Cannot interpolate vm.value in template - AngularJS

I am updating and modifying a project using Angular JS 1.2.25.
I have my controller where I have a value called vm.stageValue which is then called in template with an ng-if, so when the vm.stageValue increments it shows different containers. But whhen I define a value on the vm object that I want to interpolate on the template, eg a string that will be used and will not change on the template, I cannot seem to get it display.
This has makes me think I have not set up my controller correctly using the vm method.
It seems weird that I can use the ng-if and call function from the controller using ng-click on the template but I cannot interpolate a string or send it to another child component
Code is below, thank you in advance. Any help would be hugely appreciated
Controller
angular
.module('formModule')
.controller('NewBusinessFormCtrl', [
function() {
let vm = this;
// Methods used in controller
vm.methods = {
incrementStageValue: incrementStageValue,
decrementStageValue: decrementStageValue,
canIncrement: canIncrement,
canDecrement: canDecrement
};
//Initial stage values
vm.stageValue = 1;
vm.maxStageValue = 7;
// This is the string that I want to interpolate below
vm.contactFormCategory = 'New Business';
}
]);
Template of Controller
<div class="new_busines_cf" ng-controller="NewBusinessFormCtrl as vm">
<div class="form_wrapper">
<div ng-if="vm.stageValue == 1">
<input-text
class="form_input"
ng-model="ngModel"
input-text-label="This is the label">
</input-text>
// I want to send the vm.contactFormCategory into the component
// Value is sending but the component display 'vm.contactFormCategory'
// Not the value set in the controller
<form-headline
form-headline-sup-title="vm.contactFormCategory"
form-headline-text="This is a form headline text">
</form-headline>
</div>
// Trying to interpolate value here into template, but nothing display
{{vm.contactFormCategory}}
<div ng-if="vm.stageValue == 2">
<input-text
class="form_input"
ng-model="ngModel"
input-text-label="This is the label of stage 2">
</input-text>
<form-headline
form-headline-sup-title="vm.contactFormCategory"
form-headline-text="This is a form headline text">
</form-headline>
</div>
<button ng-click="vm.methods.incrementStageValue()">Increment Value</button>
<button ng-click="vm.methods.decrementStageValue()">decrement Value</button>
</div>
</div>
** Form Headline **
angular
.module('formModule')
.directive('formHeadline', function() {
return {
restrict: 'E',
templateUrl: '/partials/form/form-headline.component.html',
scope: {
formHeadlineText: '#',
formHeadlineSupTitle: '#'
},
link: function () {
}
};
});
Change your ng-if to
<div ng-if="vm.stageValue === '2'">

AngularJS: wait that context is loaded before write HTML

When the input select is loaded in an HTML form, sometimes the data get from the back-end is not ready and the select is displayed without any option selected.
Could be possible to wait that the data is loaded before write the input select in the page?
or there are any other way to select the right option depending on the angular value.
PS. i can't change the data that i get from the back-end and that are una array for the all value and another variable with the selected option. The first one is always loaded correctly but sometimes the second one is empty when i want to select an option.
thanks
I assume you're using asynchronous methods to load the data. In such case, the following should work.
First, have such markup:
<div ng-show="loading">
Loading, please wait...
<!-- can also put gif animation instead -->
</div>
<select ng-hide="loading">...</select>
And in the controller:
$scope.loading = true;
GetData().then(function() {
$scope.loading = false;
}, function() {
$scope.loading = false;
alert('error');
});
This assumes you load the data in a function that returns a Promise, you can of course just put the $scope.loading = false; line in the proper location in your code, after the data is actually loaded.
The effect will be that while $scope.loading is set to true, the user will see the "Loading" message while the drop down is hidden, and when you set it to false, the drop down will become visible while the "Loading" message will become hidden.
Try to get access after event stateChangeSuccess
$scope.$on('$stateChangeSuccess', function() {
(function() {
})();
});
That is how I fix this problem using AngularJS, Angular Resource & Ui-router to display selected object in an entity with Relationship:
Given that we have to entity in a simple relationship:
Class: name(String), level(String). ----> A class in school.
Child: name(String), pseudo(String). ----> A Child.
A child can be in one class at a time and there is many classes in school.
So We can have something like this(a One-To-One):
Class: name(String), level(String). ----> A class in school.
Child: name(String), pseudo(String), class(Class). ----> A Child.
In my Ui-router state I do something like this when editing a Child:
That is the state of the child to edit, when click on a link corresponding to it we query him and use a controller to resolve the entity related to him.
.state('child-edit', {
parent: 'entity',
url: '/child/{id:int}',
views: {
'content#': {
templateUrl: 'path/to/chil/view/child-edit.html',
controller: 'ChildEditController'
}
},
resolve: {
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('child');
return $translate.refresh();
}],
entity: ['$stateParams', 'ChildService', function($stateParams, ChildService) {
// We return the child to edit using a service.
return ChildService.get({id : $stateParams.id});
}]
}
})
That is the controller I use to make this run normally:
angular.module('myApp').controller('ChildEditController',
['$scope', '$stateParams', '$q', 'entity', 'ClassService',
function($scope, $stateParams, $q, entity, ClassService) {
// We get all classes of school here.
$scope.classes = ClassService.query();
// That is the promise of child to edit get from resolve in state.
$scope.childToEdit = entity;
$q.all([$scope.classes.$promise, $scope.childToEdit.$promise]).then(function() {
// When all data are resolved
// In Js two objects with same properties and valyes but different memory allocation are different.
// So I test value of Id before setting the right class of this child and angular will make able to edit
// him in the UI with the ng-model
var classOfChild = $scope.childToEdit.class;
for (var k in $scope.classes) {
if ($scope.classes[k].id === classOfChild.id) {
// We put the same reference of this class: then it will be selected in the UI of select box
$scope.childToEdit.class = $scope.classes[k];
}
}
});
}]);
And the associated UI in HTML:
<!-- The name of Child -->
<div class="form-group">
<div class="col-md-4">
<label for="field_child_name">Name of Child</label>
<input type="text" class="form-control" name="name" id="field_child_name"
ng-model="childToEdit.name"
required />
</div>
</div>
<!-- Selected class of child will be display here with all other classes available -->
<div class="form-group">
<div class="col-md-4">
<label for="field_child_class">Class of Child</label>
<select class="form-control" id="field_child_class" name="class" ng-model="childToEdit.class" ng-options="class as class.name + ' : ' + class.level for class in classes">
<option value=""></option>
</select>
</div>
</div>
Note: Hope it is the same situation where the selected data is not displaying because the references of querying class and property class in child object are different.

Can Siblings Controllers communicate with each other without the help of the Parent - AngularJS

I'm working on a small app in AngularJS. My project contain a Body.html file that contain 3 views: SideMenu, Header and Content, each with each own Controller and a MainController as there parent - the controller of the Body.html.
Can the header's controller change a property in the side-menu - the open/close status of the side-menu.
And Can the side-menu controller change a property in the header - the header's text.
I can use the main controller, since both of the header's controller and the side-menu controller can reference the main controller. But the data won't be consist. Updating the data from the 1st controller wan't effect the data in the 2nd controller (without the use of $watch).
Can both the side-menu's controller and the header's controller (sibling controllers) communicate with each other? without the help of there parent?
Body.html
<div>
<!-- Header placeholder -->
<div ui-view="header"></div>
<!-- SideMenu placeholder -->
<div ui-view="sideMenu"></div>
<!-- Content placeholder -->
<div ui-view></div>
</div>
Header.html
<div>
{{ headerCtrl.text }}
</div>
<div ng-click="headerCtrl.openSideMenu()">
--Open--
</div>
HeaderController.js
// sideMenuCtrl = ???
headerCtrl.text = "Title";
headerCtrl.openSideMenu = function()
{
sideMenuCtrl.isSideMenuOpen = true;
};
SideMenu.html
<div ng-class={ 'side-menu-open': sideMenuCtrl.isSideMenuOpen }>
<div ng-repeat="menuItem in sideMenuCtrl.sideMenuItems"
ng-click="sideMenuCtrl.selectMenuItem(menuItem)">
{{ menuItem.text }}
</div>
</div>
SideMenuController.js
// headerCtrl = ???
sideMenuCtrl.selectMenuItem = function(menuItem)
{
headerCtrl.text = menuItem.text;
}
As stated in my comment, you can use an AngularJS service to share some data between your controllers.
app.service('AppContextService', function(){
this.context = {
isSideMenuOpen: false
};
});
app.controller('SideMenuCtrl', ['$scope', 'AppContextService', function($scope, AppContextService) {
// exposing the application context object to the controller.
$scope.appContext = AppContextService.context;
}]);
app.controller('HeaderCtrl', ['$scope', 'AppContextService', function($scope, AppContextService) {
$scope.appContext = AppContextService.context;
$scope.openSideMenu = function()
{
$scope.appContext.isSideMenuOpen = true;
};
}]);
Then adapt the HTML to use your shared appContext object.
<div ng-class={ 'side-menu-open': appContext.isSideMenuOpen }>
[...]
</div>
Here is a working fiddle that illustrates the issue: fiddle
This answer covers the use of a service to fit your needs but I am sure that there are other (and perhaps better) ways to tackle the problem which might involve other Angular feature, or even some overall application refactoring.
To dig a little deeper, this SO topic might be a good start: difference between service, factory and providers

Use http cookie value in an Angular template

I have angular working in one of my ASP.NET MVC applications. I am using two html templates with Angular Routing. One is a list of current Favorites that comes from the database and is serialized into json from my Web API and used by angular to list those items from the database.
The second html template is a form that will be used to add new favorites. When the overall page that includes my angular code loads, it has a cookie named currentSearch which is holding the value of whatever the last search parameters executed by the user.
I would like to inject this value into my angular html template (newFavoriteView.html) for the value of a hidden input named and id'd searchString.
I have tried using jQuery, but had problems, plus I would much rather do this inside of angular and somehow pass the value along to my template or do the work inside the view(template). However, I know the latter would be bad form. Below is the code I think is important for one to see in order to understand what I am doing.
Index.cshtml (My ASP.NET VIEW)
#{
ViewBag.Title = "Render Search";
ViewBag.InitModule = "renderIndex";
}
<div class="medium-12 column">
<div data-ng-view=""></div>
</div>
#section ngScripts {
<script src="~/ng-modules/render-index.js"></script>
}
Setting the cookie in the MVC Controller
private void LastSearch()
{
string lastSearch = null;
if (Request.Url != null)
{
var currentSearch = Request.Url.LocalPath + "?" +
Request.QueryString;
if (Request.Cookies["currentSearch"] != null)
{
lastSearch = Request.Cookies["currentSearch"].Value;
ViewBag.LastSearch = lastSearch;
}
if (lastSearch != currentSearch)
{
var current = new HttpCookie("currentSearch", currentSearch){
Expires = DateTime.Now.AddDays(1) };
Response.Cookies.Set(current);
var previous = new HttpCookie("lastSearch", lastSearch) {
Expires = DateTime.Now.AddDays(1) };
Response.Cookies.Set(previous);
}
}
}
render-index.js
angular
.module("renderIndex", ["ngRoute"])
.config(config)
.controller("favoritesController", favoritesController)
.controller("newFavoriteController", newFavoriteController);
function config($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "/ng-templates/favoritesView.html",
controller: "favoritesController",
controllerAs: "vm"
})
.when("/newsearch", {
templateUrl: "/ng-templates/newFavoriteView.html",
controller: "newFavoriteController",
controllerAs: "vm"
})
.otherwise({ redirectTo: "/" });
};
function favoritesController($http) {
var vm = this;
vm.searches = [];
vm.isBusy = true;
$http.get("/api/favorites")
.success(function (result) {
vm.searches = result;
})
.error(function () {
alert('error/failed');
})
.then(function () {
vm.isBusy = false;
});
};
function newFavoriteController($http, $window) {
var vm = this;
vm.newFavorite = {};
vm.save = function () {
$http.post("/api/favorites", vm.newFavorite)
.success(function (result) {
var newFavorite = result.data;
//TODO: merge with existing topics
alert("Thanks for your post");
})
.error(function () {
alert("Your broken, go fix yourself!");
})
.then(function () {
$window.location = "#/";
});
};
};
favoritesView.html
<div class="container">
<h3>New Favorite</h3>
<form name="newFavoriteForm" ng-submit="vm.save()">
<fieldset>
<div class="row">
<div class="medium-12 column">
<input name="searchString" id="searchString" type="hidden"
ng-model="vm.newFavorite.searchString"/>
<label for="title">Name</label><br />
<input name="title" type="text"
ng-model="vm.newFavorite.name"/>
<label for="title">Description</label><br />
<textarea name="body" rows="5" cols="30"
ng-model="vm.newTopic.description"></textarea>
</div>
<div class="medium-12 column">
<input type="submit" class="tiny button radius" value="Save"/> |
Cancel
</div>
</div>
</fieldset>
</form>
</div>
My current attepts have been using jQuery at the end of the page after Angular has loaded and grab the cookie and stuff it in the hidden value. But I was not able to get that to work. I also thought about setting the value as a javascript variable (in my c# page) and then using that variable in angular some how. AM I going about this the right way?
Or should it be handled in the angular controller?...
I'm new to angular and the Angular Scope and a bit of ignorance are getting in the way. If any other info is needed I can make it available, thanks if you can help or guide me in the right direction.
You can do it by reading the cookie value using JavaScript, set it as a property of the $scope object and access it on the template.
//Inside your controllers
function favoritesController($http, $scope) {
//Get the cookie value using Js
var cookie = document.cookie; //the value is returned as a semi-colon separated key-value string, so split the string and get the important value
//Say the cookie string returned is 'currentSearch=AngularJS'
//Split the string and extract the cookie value
cookie = cookie.split("="); //I am assuming there's only one cookie set
//make the cookie available on $scope, can be accessed in templates now
$scope.searchString = cookie[1];
}
EXTRA NOTE
In AngularJS, the scope is the glue between your application's controllers and your view. The controller and the view share this scope object. The scope is like the model of your application. Since both the controller and the view share the same scope object, it can be used to communicate between the two. The scope can contain the data and the functions that will run in the view. Take note that every controller has its own scope. The $scope object must be injected into the controller if you want to access it.
For example:
//inject $http and $scope so you can use them in the controller
function favoritesController($http, $scope) {
Whatever is stored on the scope can be accessed on the view and the value of a scope property can also be set from the view. The scope object is important for Angular's two-way data binding.
Sorry if I'm misunderstanding or over-simplifying, but...assuming JavaScript can read this cookie-value, you could just have your controller read it and assign it to a $scope variable?
If JavaScript can't read the value, then you could have your ASP write the value to a JavaScript inline script tag. This feels yuckier though.
Update to show controller-as example.
Assuming your HTML looked something vaguely like this:
<div ng-controller="MyController as controller">
<!-- other HTML goes here -->
<input name="searchString" id="searchString" type="hidden" ng-model="controller.data.currentSearch"/>
Then your controller may look something like this:
app.controller('MyController', function ($scope, $cookies) {
$scope.data = {
currentSearch: $cookies.currentSearch
};
// Note that the model is nested in a 'data' object to ensure that
// any ngIf (or similar) directives in your HTML pass by reference
// instead of value (so 2-way binding works).
});

Dynamically creating kendo-grid columns in angular controller

I am trying to dynamically build the structure of a kendo-angular grid. My problem is that the grid options are not known when the k-options attribute is evaluated, so the grid is binding to ALL of the columns on the datasource.
Here is the HTML:
<div kendo-grid k-options="{{gridModel.options}}"
k-data-source="gridModel.myDataSource">
</div>
And here is the javascript in the controller:
// this is called after the api call has successfully returned with data
function getSucceeded(){
...
$scope.gridModel.options = function(){
// function that properly builds options object with columns, etc.
}
// this is just shown for example... the data is properly loading
$scope.gridModel.myDataSource.data(ds.data());
}
The data is properly loading, but because gridModel.options was evaluated in the HTML prior to being set by the success method, it is essentially ignored and all of the columns from the datasource are being rendered.
This works like a champ when gridModel.options is static.
How can I defer the evaluation of k-options and/or force a reevaluation after they've been set by the controller?
I was able to figure it out. I had to do four things:
Update my version of angularjs (I was on 1.08 which does not have the ng-if directive). I updated to 1.2.0rc3.
Wrap my kendo-grid div in an ng-if div
Invoke my function! I was just setting $scope.gridModel.options to a function - I needed to actually invoke the function so I'd be setting the variable to the value returned from the function.
I had to update my angular.module declaration to include ngRoute (based on it being separated into it's own module in 1.2.x).
Here's the updated HTML:
<div data-ng-if="contentAvailable">
<div kendo-grid k-options="{{gridModel.options}}"
k-data-source="gridModel.myDataSource">
</div>
</div>
And here's the updated controller (not shown: I set $scope.contentAvailable=false; at the beginning of the controller):
// this is called after the api call has successfully returned with data
function getSucceeded(){
...
$scope.gridModel.options = function(){
// function that dynamically builds options object with columns, etc.
}(); // <----- NEED to invoke function!!
// this is just shown for example... the data is properly loading
$scope.gridModel.myDataSource.data(ds.data());
$scope.contentAvailable=true; // trigger the ng-if
}
I actually moved the function into a config file so I'm not polluting the controller with too much configuration code. Very happy to have figured this out.
Here is a sample using 'Controller As' syntax, dynamic columns and paging.
var app = angular.module("app", ["kendo.directives"]);
function MyCtrl() {
var colsList = [{
name: "col1"
}, {
name: "col2"
}, {
name: "col3"
}, {
name: "col4"
}];
var gridCols = [];
var iteration = 1;
var vm = this;
vm.gridOptions = {
columns: gridCols,
dataSource: new kendo.data.DataSource({
pageSize: 10
}),
pageable: true
};
vm.buildGrid = function() {
var data = {};
vm.gridOptions.columns = [];
for (var x = 0; x < colsList.length; x++) {
if (iteration % 2 === 0 && x === colsList.length - 1) continue;
var col = {};
col.field = colsList[x].name;
col.title = colsList[x].name;
data[col.field] = "it " + iteration + " " + (1111 * (x + 1));
vm.gridOptions.columns.push(col);
}
// add one row to the table
vm.gridOptions.dataSource.add(data);
iteration++;
};
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.default.min.css" />
<script src="http://cdn.kendostatic.com/2015.1.318/js/kendo.all.min.js"></script>
<body ng-app="app">
<div ng-controller="MyCtrl as vm">
<button ng-click="vm.buildGrid()">Build Grid</button>
<div kendo-grid="grid" k-options="vm.gridOptions" k-rebind="vm.gridOptions"></div>
</div>
</body>
We can use the k-rebind directive for this. From the docs:
Widget Update upon Option Changes
You can update a widget from controller. Use the special k-rebind attribute to create a widget which automatically updates when some scope variable changes. This option will destroy the original widget and will recreate it using the changed options.
Apart from setting the array of columns in the GridOptions as we normally do, we have to hold a reference to it:
vm.gridOptions = { ... };
vm.gridColumns = [{...}, ... ,{...}];
vm.gridOptions.columns = vm.gridColumns;
and then pass that variable to the k-rebind directive:
<div kendo-grid="vm.grid" options="vm.gridOptions" k-rebind="vm.gridColumns">
</div>
And that's it when you are binding the grid to remote data (OData in my case). Now you can add or remove elements to/from the array of columns. The grid is going to query for the data again after it is recreated.
When binding the Grid to local data (local array of objects), we have to somehow postpone the binding of the data until the widget is recreated. What worked for me (maybe there is a cleaner solution to this) is to use the $timeout service:
vm.gridColumns.push({ ... });
vm.$timeout(function () {
vm.gridOptions.dataSource.data(vm.myArrayOfObjects);
}, 0);
This has been tested using AngularJS v1.5.0 and Kendo UI v2016.1.226.

Categories

Resources