How to wait till data is assigned to model in Angularjs? - angularjs

I have a model which I use to iterate and create a tabular structure on my view. I have a button on click of which I have to get the latest value from DB and assign to model. Then I get the innerHTML of model and create a pdf of my current view.
I am facing a issue that before the data is completely assigned to model and view is refreshed the next statement to get the innerHTML of container div executes and I get the older snapshot of my view. How can I hold the execution of my statement until model is done with assignment and view has refreshed?

You should wrap your code in $timeout. This will make sure that your code is executed in the next cycle and you will get the latest snapshot.
$timeout(function(){
<your code to get innerHtml>
})
There is no need to mention any timeout value as this will be called once view has changed
PS: Add $timeout as dependency.

I would use the ng-show from angular and display your content only when the data is loaded in the controller:
HTML:
<div ng-app="myApp" ng-controller="myCtrl" data-ng-init="getValues()">
<div ng-show="dataLoaded">
<input type="number" ng-repeat="(key, value) in randomArray track by $index" ng-model="randomArray[key]">
</div>
</div>
CONTROLLER:
.controller('myCtrl', function($scope) {
$scope.getValues = function() {
$scope.randomArray = ['myKey', 'anotherKey', 'thirdKey', 'key4'];
angular.forEach($scope.randomArray, function(value, key){
$scope.randomArray[key] = 0;
});
// Set dataLoaded to true
$scope.dataLoaded = true;
}
});
CODEPEN: http://codepen.io/giannidk/pen/KrmgNL?editors=1011

Related

multiple inputs based on array

My angular experience is basically about 3 days part time, so there's probably something simple I'm missing here.
I'm trying to create a dynamic list of multiple inputs based on an array, which I then want to reference from elsewhere in the app. What I've tried is loading a template from a custom directive, then $compile-ing it.
<input data-ng-repeat="term in query" data-ng-model="term">
My controller contains $scope.query = [""] which successfully creates the first empty input box. But the input box doesn't seem to update $scope.query[0] when I modify it. This means that when I try to create another empty input box with $scope.query.push(""); (from a keypress listener looking for the "/" key) I get a "duplicates not allowed" error.
I've tried manually listening to the inputs and updating scope.$query based on their value, but that doesn't feel very "angular", and results in weird behaviour.
What do I need to do to link these values. Am I along the right lines or way off?
I made a simple jsfiddle showing how to use an angular model (service) to store the data. Modifying the text inputs will also modify the model. In order to reference them somewhere else in your app, you can include TestModel in your other controllers.
http://jsfiddle.net/o63ubdnL/
html:
<body ng-app="TestApp">
<div ng-controller="TestController">
<div ng-repeat="item in queries track by $index">
<input type="text" ng-model="queries[$index]" />
</div>
<br/><br/>
<button ng-click="getVal()">Get Values</button>
</div>
</body>
javascript:
var app = angular.module('TestApp',[]);
app.controller('TestController', function($scope, TestModel)
{
$scope.queries = TestModel.get();
$scope.getVal = function()
{
console.log(TestModel.get());
alert(TestModel.get());
}
});
app.service('TestModel', function()
{
var queries = ['box1','box2','box3'];
return {
get: function()
{
return queries;
}
}
});

Update directive variable from controller

New to AngularJS I have a simple directive, service and controller. I loop through a list of items from a database in the controller embedded in the directive to render a checkbox list of items. From a form I am able to update my list of items in the database. I would at the same time like to update my list of displayed items with the newly added item and was hoping to benefit from Angulars two-way binding but I can't figure out how...
My directive:
angular.module('myModule').directive('menu', function (menuService) {
return {
restrict: 'E',
templateUrl: '../templates/menu.html',
controller: function () {
var me = this;
menuService.getMenuItems().then(function(data) {
me.items = data;
});
},
controllerAs: 'menu'
};
});
and corresponding html:
<div ng-repeat="item in menu.items">
<div class="col-md-4" ng-if="item.menuItem">
<div class="checkbox">
<label for="{{item._id}}">
<input id="{{item._id}}" type="checkbox" name="menuItems" ng-model="menuItems[$index]" ng-true-value="{{item._id}}">
{{item.menuItem}}
</label>
</div>
</div>
</div>
My issue is now that if I add a new item using this controller
EDIT: On my page I have two things. 1: A list of items rendered using the directive above and 2: A simple form with a single input field. I enter a new menuItem and click "Save". That triggers the controller below to be called with the new menuItem. The menuItem is then added to a collection in my database but I would like the list on my page to update with the newly added item. Preferably without having to reload the entire page.
$scope.insertMenuItem = function () {
$http.post('/menuItems', $scope.formData)
.success(function (data) {
$scope.items = data;
});
};
then the "me.items" in my directive remains unchanged hence so does my list in my browser.
How do I "tie it all together" so that when I call insertMenuItem then my.items are updated automagically?
This didn't come out as well as I had hoped but I hope you get the meaning...
Thanks in advance
take a look at this http://jsbin.com/rozexebi/1/edit, it shows how to bind a list of items in a directive to a controller, hope it helps.

AngularJS - Using a Service as a Model, ng-repeat not updating

I'm creating an ajax search page which will consist of a search input box, series of filter drop-downs and then a UL where the results are displayed.
As the filters part of the search will be in a separate place on the page, I thought it would be a good idea to create a Service which deals with coordinating the inputs and the ajax requests to a search server-side. This can then be called by a couple of separate Controllers (one for searchbox and results, and one for filters).
The main thing I'm struggling with is getting results to refresh when the ajax is called. If I put the ajax directly in the SearchCtrl Controller, it works fine, but when I move the ajax out to a Service it stops updating the results when the find method on the Service is called.
I'm sure it's something simple I've missed, but I can't seem to see it.
Markup:
<div ng-app="jobs">
<div data-ng-controller="SearchCtrl">
<div class="search">
<h2>Search</h2>
<div class="box"><input type="text" id="search" maxlength="75" data-ng-model="search_term" data-ng-change="doSearch()" placeholder="Type to start your search..." /></div>
</div>
<div class="search-summary">
<p><span class="field">You searched for:</span> {{ search_term }}</p>
</div>
<div class="results">
<ul>
<li data-ng-repeat="item in searchService.results">
<h3>{{ item.title }}</h3>
</li>
</ul>
</div>
</div>
</div>
AngularJS:
var app = angular.module('jobs', []);
app.factory('searchService', function($http) {
var results = [];
function find(term) {
$http.get('/json/search').success(function(data) {
results = data.results;
});
}
//public API
return {
results: results,
find: find
};
});
app.controller("SearchCtrl", ['$scope', '$http', 'searchService', function($scope, $http, searchService) {
$scope.search_term = '';
$scope.searchService = searchService;
$scope.doSearch = function(){
$scope.searchService.find($scope.search_term);
};
$scope.searchService.find();
}]);
Here is a rough JSFiddle, I've commented out the ajax and I'm just updating the results variable manually as an example. For brevity I've not included the filter drop-downs.
http://jsfiddle.net/XTQSu/1/
I'm very new to AngularJS, so if I'm going about it in totally the wrong way, please tell me so :)
In your HTML, you need to reference a property defined on your controller's $scope. One way to do that is to bind $scope.searchService.results to searchService.results once in your controller:
$scope.searchService.results = searchService.results;
Now this line will work:
<li data-ng-repeat="item in searchService.results">
In your service, use angular.copy() rather than assigning a new array reference to results, otherwise your controller's $scope will lose its data-binding:
var new_results = [{ 'title': 'title 3' },
{ 'title': 'title 4' }];
angular.copy(new_results, results);
Fiddle. In the fiddle, I commented out the initial call to find(), so you can see an update happen when you type something into the search box.
The problem is that you're never updating your results within your scope. There are many approaches to do this, but based on your current code, you could first modify your find function to return the results:
function find(term) {
$http.get('/json/search').success(function(data) {
var results = data.results;
});
//also notice that you're not using the variable 'term'
//to perform a query in your webservice
return results;
}
You're using a module pattern in your 'public API' so your searchService returns the find function and an array of results, but you'd want to make the function find to be the responsible for actually returning the results.
Setting that aside, whenever you call doSearch() in your scope, you'd want to update the current results for those returned by your searchService
$scope.doSearch = function(){
$scope.searchService.results = searchService.find($scope.search_term);
};
I updated your jsfiddle with my ideas, is not functional but i added some commments and logs to help you debug this issue. http://jsfiddle.net/XTQSu/3/

DOM not rendered when executing run block

I want to show a "Loading..." message while loading json data in my AngularJS app. Showing the message and loading the data is done in my main module's run block. The problem is that the browser hasn't rendered the DOM when the run block is executed so the message is not shown. When exactly is the run block executed? How could I achieve what I want: first show the page, then start loading data and display a message?
My code is here: www.esatoivola.net/kirkkovuosi
"When exactly is the run block executed?"
Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time. -- Module docs
.
"How could I ... first show the page, then start loading data and display a message?"
You could use ng-show and a $scope or $rootScope property (initially set to true) to control showing the "Loading" message. Your main controller can load the data, and when the data comes back, set some $scope property tied to the view and set the "showLoadingMessage" property to false.
HTML:
<div ng-controller="MyCtrl">
<div ng-show="showLoadingMessage">Loading... </div>
<ul>
<li ng-repeat="item in data">
....
</li>
</ul>
</div>
Controller:
function MyCtrl($scope, $resource) {
$scope.showLoadingMessage = true;
var dataResource = $resource('/somewhere/else');
dataResource.query( function(data) {
$scope.showLoadingMessage = false;
$scope.data = data;
});
}

Getting to bound data in Angular.js

Is there a way in angular to get binding back from a template?
In other words, if I have something like this:
<div ng-repeat="item in list">
<div>{{item.name}}</div>
<div>{{item.state}}</div>
</div>
would it be possible to change the item's state by clicking on it, because the repeated div would "remember" what item it was built from?
Yes, you can use the ng-click directive to trigger a method on the current scope:
// In your view's controller:
function MyCtrl($scope, MyList) {
// You probably have something like that already to
// populate your list, using a $resource or $http GET call.
// Here I use a $resource which would be defined on your module.
$scope.list = MyList.query()
$scope.setState = function(state) {
// "this" refers to the current scope
this.item.state = state
}
}
// And in your view:
<div ng-repeat="item in list">
<div>{{item.name}}</div>
<div ng-click="setState('whatever')">{{item.state}}</div>
</div>
Or you can simply set an expression such as ng-click="item.state='whatever'" directly on the div, although this is less testable - only in end-to-end tests - and less flexible, say you want to introduce validation or something).
HTH

Resources