Angularjs data binding with a data attribute object - javascript

I have some json attached to a data attribute on a page. The json data is used to build a table in angularjs.
I'm using coffeescript and haml.
app = angular.module("myApp", [])
app.controller "TableCtrl", ($scope) ->
$scope.table = $("#mydata").data("myjson")
#table{"ng-app"=>"myApp","ng-controller" =>"TableCtrl"}
%table
%tbody
%tr{"ng-repeat"=>"(i,item) in table" }}"}
%td {{item.name}}
The page loads the data into a table. Elsewhere on the page the json on the data attribute can be changed by a user with jquery. How can I have 2-way binding between the json data and the table? i.e I want the table to change as the json on the data attribute is changed locally.

What you need is to tell AngularJS to observe $("#mydata").data("myjson") for any changes and then update $scope.table when a change occurs. Try adding the following code to your controller (sorry I don't know coffeescript).
$scope.$watch(
function () { return $("#mydata").data("myjson");},
function(newJson) {
$scope.table = newJson;
},
true
);

Related

exposing angularjs grid data from one controller into another

I'm trying to push data from a link within my grid data UI, when you click the link, open a popup (which I do with a modal fine) however when the modal opens, I can't access any of the data that was defined in the other controller.
This snippet:
<a href ng-click="grid.appScope[col.field](row.entity)">Popup</a>
Works fine, where it shows the col.field value, however I'd like to show data within the popup from grid.appScopecol.field in the popup - however that is another controller, how would I handle passing data from one controller to another within this format?
My suggestion is just pass those data into angular service define a service like
angular.service('MyService', function() {
//if you want Object format or
this.controller1Data = {};
//if you want array format
this.controller1Data = {};
});
in your controller just pass the data into that service like
//In controller
MyService.controller1Data = //Pass the data to that service;
then in HTMl
<a href ng-click="//call that method()">Popup</a>

Angular select multiple not refreshing on model change

I have the following issue with angular and the html select-input:
When the user loads the page my select is empty until the data is loaded and returned from the corresponding service.
In this case the select is populated correctly.
However, the user should be able to filter the model with a click on a button.
When I press the button a new request is send to the REST-API and the response contains the new model for the select.
Unfortunately, the select won't update correctly even when I change it's model
Here is some code to illustrate my problem:
// This happens in my controller
EventService.getAvailableRooms(requestObject).then(function successCallback(response){
// sanatizeRoomTypes is used to generate user-friendly names instead of [1, 2,..]
vm.rooms = DataSanatizer.sanatizeRoomTypes(response.data);
}, function errorCallback(response){
console.log(response)
});
vm.rooms is the model of my select:
<select id="roomSelect" ng-model="eventCtrl.selectedRooms"
ng-options="room.name group by room.type for room in eventCtrl.rooms track by room.id" multiple required>
</select>
In some cases the select duplicates it's model or looses entries. It seems like there is some sort of data binding problem.
Thanks,
Try wrapping your model changes in $scope.apply :
$scope.$apply(function() {
$scope.data.myVar = "Another value";
});
Read here for more info:
http://tutorials.jenkov.com/angularjs/watch-digest-apply.html
You can also use $scope.$watch on the changing $scope variables to update them in your view.

How to post data to Google Fusion Tables automatically AngularJS/Javascript?

I want to create a map with polygons using Google Fusion Tables. Instead of importing the data manually each time when there are new entries, I want to automatize it with AngularJS/Javascript.
My question is, how do I post and handle (through a controller or factory) the data automatically to a Fusion Table in AngularJS/Javascript? Does anyone know a good example or way to start? Do I need to work with JSON and if so how would that look like?
EDIT:
I already have retrieved the data from another API with the following controller:
.controller('DataCtrl', function($scope, $http) {
$scope.entries = [];
$http.get('main.json').success(function(data) {
angular.forEach(data.ParkingFacilities, function(entry) {
$http.get(entry.staticDataUrl).success(function(data) {
$scope.entries.push(angular.extend(entry, data.parkingFacilityInformation));
});
});
});
});
An example of the JSON file is available here: https://npropendata.rdw.nl/parkingdata/v2/

see model data from controller in View [sap ui5]

I've created a JSON model in a controller, and I have nice data list there...
but I do not know how to access this list/model via corresponding view. Help?
You can set model in controller:
`sap.ui.getCore().setModel(jsonModel,"NAME");`
and get this model in View (JS view) with:
`sap.ui.getCore().getModel("NAME");`

AngularJS POSTs empty requests?

I'm a newbie in AngularJS and I've faced an issue when I try to make a POST request with AngularJS and it POSTs no parameters with it. I use Sinatra as a RESTful interface.
That's how my Sinatra backend looks:
post '/layer/:layer_id' do
#layer = PageLayer.where(id: params[:layer_id]).first
#layer.content = params[:content]
#layer.save
end
If try to POST with Postman chrome extension - it works! Sinatra saves the content properly. So I'm sure that the backend works as it should.
That's how my angular test code looks:
TestCtrl = ($scope, $routeParams, $http, $resource) ->
$scope.layer = []
Layer = $resource('/layer/:id', {id:'#id'})
$scope.layer = Layer.get {id: $routeParams.layerId}, ->
console.log "Got you!"
$scope.saveContent = ->
$scope.layer.$save()
console.log "Saved!"
angular.module('appDirectives', []).directive "test", ->
return (scope, element, attrs) ->
element.bind "blur", ->
console.log("blur!")
scope.saveContent()
And HTML-code:
<div>Content: {{layer.content}}</div>
<div>
<form>
<input type="text" test ng-model="layer.content">
</form>
</div>
So, the only question is: What's wrong? Why I can make correct request with Postman but not with angularJS? Angular returns empty "content" so Sinatra saves it as "" every time.
I've also attached a structure of a layer:
g {id: 27245, page_id: 2302, external_id: 26518, original_upload: null…}
content: "dfgdfg"
external_id: 26518
id: 27245
layerNumber: 8
page_id: 2302
How can I log what exactly angular POSTs?
Hey this is the exact problem I was having, and the answer now seems so obvious. I knew Angular was sending json, but no matter what I tried it wasn't working. This led me in the right direction, but as for parsing json I had to write
ng_params = JSON.parse(request.body.read)
I had to change 'string' to 'read'. Maybe I have a newer version of the json gem or something. My full save process is like this:
post '/api/v1/test' do
ng_params = JSON.parse(request.body.read)
#foo = Foo.new(ng_params)
if #foo.save
puts "Page Saved"
content_type :json
rabl :foos, format: "json"
end
end
I use rabl to format the json to have control over what json data Sinatra sends back (no emails or passwords please)
My Angular code is just this (have not yet implemented put, patch or delete, nor auto update of data just yet. You still have to refresh the page to see the new post.) And to be clear, I have a table named 'foos', where the ActiveRecord model is 'Foo', and one column named 'anything' (other than timestamps and id, which I make sure are always there).
// app declaration
var app = angular.module("App", ['ngResource']);
// data service
app.factory('Foo', ['$resource', function($resource) {
return $resource('/api/v1/test/:id', {id: '#id'});
}]);
// the controller
app.controller('Controller', function($scope, Foo) {
$scope.foos = Foo.query();
$scope.create = function(anything) {
Foo.save({anything: anything}, function(foo){
$scope.foos.push(foo);
});
};
});
Then in my markup the form looks like this, where the important thing is the call to 'create' with 'anything' as the argument in 'ng-submit'. If you have more than one column in your table you call 'create' with more than one argument ex. 'create(anything, bar)'.
<h3>Add something new</h3>
<form ng-submit="create(anything)">
<input ng-model="anything" type="text">
<button type="submit">Do it</button>
</form>
While displaying the data is
<li ng-repeat="foo in foos">
<p>{{foo.anything}}</p>
</li>
This link solved the problem. Just add
gem 'rack-parser'
to your Gemfile and add this code to config.ru. Will work like a charm.
require 'rack/parser'
use Rack::Parser, content_types: {
'application/json' => Proc.new {|body| JSON.parse body }
}
All right, I've solved the issue. Somehow Sinatra was not properly getting POSTs from Angular and was not automatically putting them into params.
So if we parse the request manually - it works. Like that:
post '/layer/:layer_id' do
#updated_layer = JSON.parse(request.body.string)
#layer = PageLayer.where(id: params[:layer_id]).first
#layer.content = #updated_layer['content']
#layer.save
end

Categories

Resources