ng-repeat with JSON object doesn't work - javascript

It must be the heat...
I have a json object that I want to run through a ng-repeat, should be simple, but alas! it doesn't work.
HTML
<a data-ng-repeat="x in template.menuObj" href="{{ x.link }}">{{ x.name }}</a>
JSON
[
{
"ACL":{
"*":{
"read":true
}
},
"link":"home",
"menu":"main",
"name":"Home",
"order":1,
"objectId":"aDcb0HUXwB",
"createdAt":"2015-08-05T15:29:05.948Z",
"updatedAt":"2015-08-05T15:29:11.915Z"
},
{
"ACL":{
"*":{
"read":true
}
},
"link":"category/the-interesting-stuff",
"menu":"main",
"name":"The Interesting Stuff",
"order":2,
"objectId":"znXfUF0kdJ",
"createdAt":"2015-08-05T15:33:11.332Z",
"updatedAt":"2015-08-05T15:33:39.738Z"
},
{
"ACL":{
"*":{
"read":true
}
},
"link":"category/the-fun-stuff",
"menu":"main",
"name":"The Fun Stuff",
"order":3,
"objectId":"WiPmXdhaOu",
"createdAt":"2015-08-05T15:33:44.667Z",
"updatedAt":"2015-08-05T15:34:06.058Z"
},
{
"ACL":{
"*":{
"read":true
}
},
"link":"category/the-nerdy-stuff",
"menu":"main",
"name":"The Nerdy Stuff",
"order":4,
"objectId":"Z0aSsnpV0B",
"createdAt":"2015-08-05T15:34:09.859Z",
"updatedAt":"2015-08-05T15:34:33.564Z"
},
{
"ACL":{
"*":{
"read":true
}
},
"link":"page/about-me",
"menu":"main",
"name":"About Me",
"order":5,
"objectId":"Gm35DOju7t",
"createdAt":"2015-08-05T15:34:37.759Z",
"updatedAt":"2015-08-05T15:34:55.387Z"
}
]
When I run this, I get 5 empty <a>'s, something like:
<a data-ng-repeat="x in template.menuObj" href="" class="ng-binding ng-scope"></a>
So I guess angular sees the 5 arrays, but somehow the keys are not caught?
EDIT: This is how the json object is created (via parse.com):
var Menu = Parse.Object.extend('Menu');
var query = new Parse.Query(Menu);
query.ascending('order');
query.equalTo('menu', 'main');
query.find().then(function(results){
console.log(JSON.stringify(results));
$scope.template.menuObj = results;
}, function(error){
// error-handling
console.log("Error: " + error.code + " " + error.message);
});
EDIT EDIT: Controller etc.
blogApp.controller('templateCtrl', function($scope, templateService) {
$scope.template = templateService;
var Menu = Parse.Object.extend('Menu');
var query = new Parse.Query(Menu);
query.ascending('order');
query.equalTo('menu', 'main');
query.find().then(function(results){
console.log(JSON.stringify(results));
$scope.template.menuObj = results;
}, function(error){
// error-handling
console.log("Error: " + error.code + " " + error.message);
});
});
templateService is a factory that binds a parent controller. It's important to note that before I started messing with parse.com for this project, the ng-repeat worked just fine when I retrieved ($http) a json object via PHP/MySQL.
EDIT EDIT EDIT: uploaded a screendump of console.log(results);

What's happening is that results is the array object, and you are assigning it to $scope.template.menuObj but the json array doesn't have a name. You could either give it a name:
"menuObj": [
{
"ACL":{
"*":{
"read":true
}
},
"link":"home",
"menu":"main",
"name":"Home",
"order":1,
"objectId":"aDcb0HUXwB",
"createdAt":"2015-08-05T15:29:05.948Z",
"updatedAt":"2015-08-05T15:29:11.915Z"
},
{
"ACL":{
"*":{
"read":true
}
},
"link":"category/the-interesting-stuff",
"menu":"main",
"name":"The Interesting Stuff",
"order":2,
"objectId":"znXfUF0kdJ",
"createdAt":"2015-08-05T15:33:11.332Z",
"updatedAt":"2015-08-05T15:33:39.738Z"
},
{
"ACL":{
"*":{
"read":true
}
},
"link":"category/the-fun-stuff",
"menu":"main",
"name":"The Fun Stuff",
"order":3,
"objectId":"WiPmXdhaOu",
"createdAt":"2015-08-05T15:33:44.667Z",
"updatedAt":"2015-08-05T15:34:06.058Z"
},
{
"ACL":{
"*":{
"read":true
}
},
"link":"category/the-nerdy-stuff",
"menu":"main",
"name":"The Nerdy Stuff",
"order":4,
"objectId":"Z0aSsnpV0B",
"createdAt":"2015-08-05T15:34:09.859Z",
"updatedAt":"2015-08-05T15:34:33.564Z"
},
{
"ACL":{
"*":{
"read":true
}
},
"link":"page/about-me",
"menu":"main",
"name":"About Me",
"order":5,
"objectId":"Gm35DOju7t",
"createdAt":"2015-08-05T15:34:37.759Z",
"updatedAt":"2015-08-05T15:34:55.387Z"
}
];
Or leave it like you have it, but the controller must be like this:
blogApp.controller('templateCtrl', function($scope, templateService) {
$scope.template = templateService;
var Menu = Parse.Object.extend('Menu');
var query = new Parse.Query(Menu);
query.ascending('order');
query.equalTo('menu', 'main');
query.find().then(function(results){
$scope.template = JSON.stringify(results);
}, function(error){
// error-handling
console.log("Error: " + error.code + " " + error.message);
});
});
And the view like this:
<body ng-app="blogApp"><!-- angular.module('blogApp', []); -->
<div ng-controller="templateCtrl" >
<nav ng-repeat="a in template">
{{ a.name }}
</nav>
</div>
</body>
But in the case you want to work with it as you have it you should do it this way:
<body ng-app="blogApp"><!-- angular.module('blogApp', []); -->
<div ng-controller="templateCtrl" >
<nav ng-repeat="a in template.menuObj">
{{ a.get('name') }}
</nav>
</div>
</body>

Related

trying to send some data from nodejs to script in html

I am using hbs as view in frontend.
I tried to send data to my script in html from nodejs like this :
router.get('/home',authController.isLoggedIn, (req ,res) => {
if(req.user){
db.query('SELECT * FROM posts ORDER BY id desc ', (error,results) => {
if (error) {
console.log(error);
} else {
let categories;
db.query('SELECT * FROM categories', (error,result) => {
if (error) {
console.log(error);
} else {
console.log(result);
categories = result;
return res.render('home',{
results: results,
categories: categories
});
}
});
}
});
}else {
res.redirect('/login');
}
});
then when i am trying to call it here in script using javaScript it tells me something is wrong
<script>
alert(results);
</script>
I want to know how correctly call the the object in script
edit:
the data should be something like this :
[
RowDataPacket { id: 1, category: 'Music' },
RowDataPacket { id: 2, category: 'Memes' },
RowDataPacket { id: 3, category: 'Tech' }
]
For EJS example if pass data msgs:
res.render("index.ejs", {
msgs
})
js handle data:
<p>
<%
msgs = msgs.map(function(msg) {
return '<div>' + msg.name + '</div>' + '<div>' + msg.msg + '</div>'+ '<div>' + msg.time + '</div>'
})
%>
</p>
print directly:
<p><%- msgs.join("<hr />") %></p>
save in global variable
<script>
window.serverMsgs = <%- msgs %>;
</script>
And for handlebars:
<script>
window.serverMsgs = {{msgs}};
alert(window.serverMsgs)
{{#each results}}
{
"id": {{id}},
"category": "{{category}}",
}
{{#unless #last}},{{/unless}}
{{/each}}
</script>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>{{title}} - Page Test</title>
</head>
<body>
<div class="description">{{description}}</div>
<ul>
{{#datas}}
<li class="item" id="item_{{index}}"><span>{{time}}</span>{{title}}</li>
{{/datas}}
</ul>
</body>
</html>
u could check out this similar issue:) How to define an array within a <script> tag inside a hbs view template

Accessing JSON element which has a number for the name

I have tried to access an element of the json structure but can't. I have tried the following.
I am using the npm package json-query to extract part of the bigger JSON object.
var rslt = jsonQuery('results[**][* status=active]', {
data: response
});
var make = JSON.stringify(rslt.value[0]["parms"]["make"])
Bu this does not work, I have also tried to get the following data from the JSON:
var img = JSON.stringify(rslt.value[0]["photos"]["1"]["320x240"]);
var subtitle = JSON.stringify(rslt.value[0]["parms"]["price"]["1"]) + ' EUR';
This is the JSON data I am working with:
{
"value":[
{
"id":7038271775,
"user_id":1307227,
"status":"active",
"title":"",
"url":"https://www.autovit.ro/anunt/nissan-navara-ID7GjS0w.html",
"created_at":"2017-01-06 17:49:35",
"valid_to":"2017-02-03 17:56:16",
"description":"Data inmatriculare: 02.03.2015.\r\n4x4 \r\nABS \r\nAer conditionat \r\nComputer de bord \r\nGeamuri electrice \r\nInchidere centralizata \r\nJante aliaj \r\nRadio CD \r\nServodirectie \r\nVolan multifunctional",
"category_id":29,
"region_id":46,
"city_id":24691,
"city":{
"ro":"Voluntari",
"en":"Voluntari"
},
"coordinates":{
"latitude":44.49192877,
"longitude":26.12458706,
"radius":0,
"zoom_level":16
},
"advertiser_type":"business",
"contact":{
"person":"LeasePlan Outlet Center",
"phone_numbers":[
"0753312151"
]
},
"params":{
"make":"nissan",
"model":"navara",
"year":2014,
"mileage":16785,
"engine_capacity":2500,
"vin":"VSKCVND40U0566467",
"fuel_type":"diesel",
"gearbox":"manual",
"transmission":"all-wheel-lock",
"particle_filter":"0",
"green_tax":"1",
"damaged":"0",
"body_type":"suv",
"door_count":4,
"color":"white",
"metallic":"0",
"pearl":"0",
"matt":"0",
"rhd":"0",
"features":[ ],
"price":{
"0":"price",
"1":15900,
"currency":"EUR",
"gross_net":"net"
},
"vat":"1",
"financial_option":"1",
"leasing_concession":"0",
"date_registration":"2014-1-01",
"registered":"1",
"original_owner":"1",
"no_accident":"0",
"service_record":"0",
"historical_vehicle":"0",
"tuning":"0"
},
"photos":{
"1":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_1_1080x720.jpg",
"732x488":"https://img40.autovit.ro/images_autovitro/820558483_1_732x488.jpg",
"320x240":"https://img42.autovit.ro/images_autovitro/820558483_1_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_1_148x110.jpg"
},
"2":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_2_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_2_732x488.jpg",
"320x240":"https://img42.autovit.ro/images_autovitro/820558483_2_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_2_148x110.jpg"
},
"3":{
"1080x720":"https://img42.autovit.ro/images_autovitro/820558483_3_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_3_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_3_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_3_148x110.jpg"
},
"4":{
"1080x720":"https://img42.autovit.ro/images_autovitro/820558483_4_1080x720.jpg",
"732x488":"https://img40.autovit.ro/images_autovitro/820558483_4_732x488.jpg",
"320x240":"https://img42.autovit.ro/images_autovitro/820558483_4_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_4_148x110.jpg"
},
"5":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_5_1080x720.jpg",
"732x488":"https://img41.autovit.ro/images_autovitro/820558483_5_732x488.jpg",
"320x240":"https://img41.autovit.ro/images_autovitro/820558483_5_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_5_148x110.jpg"
},
"6":{
"1080x720":"https://img40.autovit.ro/images_autovitro/820558483_6_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_6_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_6_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_6_148x110.jpg"
},
"7":{
"1080x720":"https://img40.autovit.ro/images_autovitro/820558483_7_1080x720.jpg",
"732x488":"https://img41.autovit.ro/images_autovitro/820558483_7_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_7_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_7_148x110.jpg"
},
"8":{
"1080x720":"https://img42.autovit.ro/images_autovitro/820558483_8_1080x720.jpg",
"732x488":"https://img41.autovit.ro/images_autovitro/820558483_8_732x488.jpg",
"320x240":"https://img42.autovit.ro/images_autovitro/820558483_8_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_8_148x110.jpg"
},
"9":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_9_1080x720.jpg",
"732x488":"https://img40.autovit.ro/images_autovitro/820558483_9_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_9_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_9_148x110.jpg"
},
"10":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_10_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_10_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_10_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_10_148x110.jpg"
},
"11":{
"1080x720":"https://img42.autovit.ro/images_autovitro/820558483_11_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_11_732x488.jpg",
"320x240":"https://img41.autovit.ro/images_autovitro/820558483_11_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_11_148x110.jpg"
}
},
"image_collection_id":820558483,
"last_update_date":"2017-01-24 18:00:26",
"new_used":"used"
}
],
"is_last_page":false,
"is_first_page":true,
"current_page":1,
"total_pages":33,
"current_elements":1,
"total_elements":33
}
I don't know what excatly "json-query" does but I think you can extract any JSON part safely like this;
function dig(input, key) {
var keys = (""+ key).split("."), key = keys.shift();
if (!keys.length) {
return input[key];
}
return dig(input[key], keys.join("."));
}
// here that gives me already without any error thrown >> https://img42.autovit.ro/images_autovitro/820558483_1_320x240.jpg
var p = dig(rslt, "results.0.photos.1.320x240");
console.log(p);
// this is same with
console.log(rslt.results[0].photos[1]["320x240"]);
Credits: https://github.com/yay-couch/couch-js/blob/master/couch/util/util.js#L46
i'm not sure how its not working, the only problem i see with your code is you mistaken by writing params and you write parms

Trying to access json-server data via a controller and factory in angular

I'm writing a very simple test app in angular js and am trying to display data stored on a json server to display in the view.
db.json is as follows:
{
"examples": [
{
"id": 0,
"name": "example 0",
"description": "Example 0 description."
},
{
"id": 1,
"name": "example 1",
"description": "Example 1 description."
}
]
}
controller is as follows:
angular.module('my_app')
.controller('ExampleController', ['$scope', 'exampleFactory', function ($scope, exampleFactory) {
$scope.example = exampleFactory.query({
})
.$promise.then(
function (response) {
var examples = response;
$scope.message = examples;
},
function (response) {
$scope.message = "Error: " + response.status + " " + response.statusText;
}
);
}])
factory is as follows:
.factory('exampleFactory', ['$resource', 'baseURL', function ($resource, baseURL) {
return $resource(baseURL + "examples/:id", null, {
'update': {
method: 'PUT'
}
});
}])
;
And view is as follows:
<p>Test outside repeat: {{message}}</p>
<ul>
<li ng-repeat="example in examples">
<p>Test in repeat: {{message}}</p>
<p>{{example.name}}</p>
<p>{{example.description}}</p>
</li>
</ul>
The interesting thing here is that the data is being returned by the factory. In the above example the first test (outside the ng-repeat) returns the full set. However, nothing inside ng-repeat shows up.
I've got this working using a slightly different arrangement using a service but it doesn;t seem to be working using a factory.
Does anyone have any idea why this is and could they put me right?
Thanks
Stef
I think you just forgot to assign $scope.examples, so the ng-repeat had no data to loop over:
angular.module('my_app')
.controller('ExampleController', ['$scope', 'exampleFactory', function ($scope, exampleFactory) {
$scope.example = exampleFactory.query({
})
.$promise.then(
function (response) {
var examples = response;
$scope.message = examples;
$scope.examples = examples.examples; // I may be reading the JSON wrong here.
},
function (response) {
$scope.message = "Error: " + response.status + " " + response.statusText;
}
);
}])
I'd suggest using a factory as you can get the methods inside the factory before the factory has been returned. It's the revealing module pattern, good read here if your interested JavaScript Design Patterns
angular
.module('my_app')
.controller('ExampleController', ['$scope', 'exampleFactory',
function($scope, exampleFactory) {
function getMessageList() {
exampleFactory
.getMessages()
.then(function(messages) {
$scope.examples = messages;
})
.catch(function(response) {
$scope.message = "Error: " + response.status + " " + response.statusText;
});
}
getMessageList();
}
])
.factory('exampleFactory', ['$http', 'baseURL',function($http, baseURL) {
function getMessages() {
return $http
.get(baseURL)
.then(function(jsonResp) {
return jsonResp.data;
})
.catch(function(error) {
//handle error if needed
console.log(error);
});
}
return {
getMessages: getMessages
};
}
]);
<p>Test outside repeat: {{examples}}</p>
<ul>
<li ng-repeat="example in examples">
<p>Test in repeat: {{message}}</p>
<p>{{example.name}}</p>
<p>{{example.description}}</p>
</li>
</ul>
Eventually sorted it by changing controller as follows:
.controller("ExampleController", function($scope, exampleFactory) {
exampleFactory.query(function(response) {
$scope.examples = response;
$scope.examples.$promise.then(
function (response) {
var examples = response;
$scope.message = examples;
},
function (response) {
$scope.message = "Error: " + response.status + " " + response.statusText;
}
);
});
});
Probably a little bit clunky and it would be nice to be able to reduce it further but as I'm very new to all this I'll go with this for now.

How to do CRUD operation update in angular js?

Hii i am new to angular js ,right now i am working on the crud operation in angular js , i dont know how to do update the data in angularjs which is consuming rest api calls. could you pls help me out ?
my view :
<div ng-repeat="phone in phones">
<p>{{ phone.sequenceNumber}}. {{ phone.phoneNumber }} ({{ phone.phoneType }}<span ng-if="phone.isPrimary"> primary</span>)</p>
<button ng-click="updatePhone()" ng-model="phone.phoneNumber" class="btn btn-small btn-primary">update</button>
</div>
</div>
</form>
my controller :
"use strict"
ContactApp.controller("StudentController", [
'$scope',
'$http',
'$state',
'$sce',
'UiString',
'Settings',
'EmergencyContact',
'MissingPersonContact',
'Address',
'Phone',
function($scope, $http,$state, $sce, UiString, Settings, EmergencyContact, MissingPersonContact, Address, Phone
) {
EmergencyContact.getContacts($scope.uid).then(function(contacts) {
$scope.emergencyContacts = contacts;
});
MissingPersonContact.getContacts($scope.uid).then(function(contacts) {
$scope.missingPersonContacts = contacts;
});
Address.getLocalAddress($scope.uid).then(function(address) {
$scope.localAddress = address;
});
Phone.getPhones($scope.uid).then(function(phone1) {
$scope.phones = phone1;
});
$scope.newPhoneNumber = '';
$scope.AddPhone = function() {
console.log("scope.newPhoneNumber",$scope.newPhoneNumber);
var newPhone = Phone.addPhone($scope.newPhoneNumber);
Phone.savePhone($scope.uid, newPhone).then(
function(response) {
$scope.phones.push(newPhone);
return console.log("question", response);
},
function(err) {
return console.log("There was an error "
+ err);
});
};
$scope.updatePhone = function() {
Phone.savePhone1($scope.uid, newPhone).then(
function(response) {
$scope.phones.push(newPhone);
return console.log("question", response);
},
function(err) {
return console.log("There was an error "
+ err);
});
};
}]);
my service :
'use strict';
angular.module('ContactApp')
.service('Phone', ['$q', '$http', 'Settings', function($q, $http, Settings) {
this.getPhones = function(id) {
var deferred = $q.defer();
if (id) {
$http.get(Settings.getSetting('wsRootUrl') +
'/person/phone/v1/' + id + '?token=' + Settings.getToken()).
success(function(response) {
deferred.resolve(response.data);
}).error(function(data, status) {
deferred.reject(status);
});
} else {
deferred.resolve({});
}
return deferred.promise;
};
this.addPhone = function(phoneNumber) {
var model =
{
"pidm": null,
"phoneType": "CELL",
"activityDate": null,
"isPrimary": null,
"phoneNumber": phoneNumber,
"sequenceNumber": null,
"status": null
};
return model;
}
this.savePhone = function(userId, phone) {
var deferred = $q.defer();
console.log(phone);
$http.post( Settings.getSetting('wsRootUrl') +
'/person/phone/v1/' + userId + '?token=' + Settings.getToken()
, [ phone ]).
success(function(response) {
deferred.resolve(response.data);
}).error(function(data, status) {
deferred.reject(status);
});
return deferred.promise;
};
this.updatePhone = function(phoneNumber1) {
var model =
{
"pidm": 123456,
"phoneType": "CELL",
"activityDate": null,
"isPrimary": null,
"phoneNumber": phoneNumber1,
"sequenceNumber": null,
"status": null
};
return model;
}
this.savePhone1 = function(userId, phone1) {
var deferred = $q.defer();
console.log(phone1);
$http.put( Settings.getSetting('wsRootUrl') +
'/person/phone/v1/' + userId + '?token=' + Settings.getToken()
, [ phone1 ]).
success(function(response) {
deferred.resolve(response.data);
}).error(function(data, status) {
deferred.reject(status);
});
return deferred.promise;
};
}]);
~~~EDIT~~~~
Okay from what I gather this is what you want:
In HTML inside of ng-repeat:
<input type="text" ng-model="phone.phoneNumber" />
// at this point when the user types their new phone number in the "phone" object has already been updated (via two-way data binding).
Then if you want to save to database you can send to your service via the controller method $scope.updatePhone with the button.
<button ng-click="updatePhone(phone)">Update</button>
Then in the controller:
$scope.updatePhone = function (phone) {
console.log("this is the updated phone: ",phone);
console.log("this is the updated phones array: ",$scope.phones);
// you should see that the phone number has been updated in scope.
Phone.updatePhone(phone);
// this service call should be a post to the server, not a return object as the object has already been updated.
}
Hope this helps
You can find example here of CRUD operation in AngularJS with Web API to perform Create, Read, Update and Delete functionality. I hope it will be help to you.
CRUD Operation in AngularJS with Web API

Time to paint angularjs menu

I have a menu that I walk with a "ng-repeat" to paint the problem that I have is that if you burn a variable with the json from the menu that is painted correctly, but if the menu as consumption from a WebAPI not paint me complete, menu is as if first paint the html consultation before the end of the WebAPI.
The menu paints me correctly, but a submenu (dropdown) does not paint me children.
They know how to solve it?
This is the menu
This is the html
<div ng-controller="dashboardController" class="nav-wrapper">
<ul ng-init="menuApp()">
<li ng-repeat="item in menus" ng-init="$last && rebindDropDowns()" class="{{item.Submenu.length ? 'dropdown-button' : ''}}" ng-bind-html="item.Nombre" data-activates="{{item.Submenu.length ? 'administracion' : ''}}">
{{item.Opcion}}
<ul ng-if="item.Submenu.length>0" id="administracion" class="dropdown-content">
<li ng-repeat="subItem in item.Submenu"><a ng-href="{{subItem.Nombre}}">{{subItem.Descripcion}}</a></li>
</ul>
</li>
</ul>
</div>
And this is the Controller
(function() {
'use strict';
angular.module('gastosDeViaje').controller('dashboardController', ['$scope', 'dashboardService', 'accesoService', 'notificaService', 'legalizacionService', '$location', '$q',
function($scope, dashboardService, accesoService, notificaService, legalizacionService, $location, $q, men) {
$scope.menuApp = function() {
accesoService.consultaMenu(accesoService.authentication.userName).then(function(result) {
$scope.menus = result.data;
console.log(result);
});
};
$scope.rebindDropDowns = function() {
console.log('entro drop');
$('.dropdown-button').dropdown();
};
$scope.menu = [{
"Opcion": "Solicitud",
"Nombre": "<i class=\"material-icons left\">flight</i>Solicitud ",
"Descripcion": "Formulario para Solicitud",
"Submenu": []
}, {
"Opcion": "Consultas",
"Nombre": "<i class=\"material-icons left\">search</i>Consultas ",
"Descripcion": "Formulario para Consultas",
"Submenu": []
}, {
"Opcion": "Transferencia",
"Nombre": "<i class=\"material-icons left\">attach_money</i>Transferencia ",
"Descripcion": "Transferencia",
"Submenu": []
}, {
"Opcion": "Administracion",
"Nombre": "<a class=\"dropdown-button\" data-activates=\"administracion\"><i class=\"material-icons left\">settings</i>Administracion<i class=\"material-icons right\">arrow_drop_down</i></a> ",
"Descripcion": "Menu de Administracion",
"Submenu": [{
"Opcion": "Reservas",
"Nombre": "#/reservas ",
"Descripcion": "Reservas",
"Submenu": null
}, {
"Opcion": "Globales",
"Nombre": "#/globales ",
"Descripcion": "Globales",
"Submenu": null
}, {
"Opcion": "Convenios",
"Nombre": "#/convenios ",
"Descripcion": "Convenios",
"Submenu": null
}, {
"Opcion": "Aplicacion",
"Nombre": "#/aplicacion ",
"Descripcion": "Aplicacion",
"Submenu": null
}]
}];
dashboardService.getEmpleadoAprobar(accesoService.authentication.userName).then(function(results) {
$scope.empleadosAprobar = results.data;
}, function() { //error
console.log('Error al Cargar los datos');
});
dashboardService.getEmpleadoAutorizar(accesoService.authentication.userName).then(function(results) {
$scope.empleadosAutorizar = results.data;
}, function() { //error
console.log('Error al cargar las autorizaciones');
});
dashboardService.getEmpleadolegalizar(accesoService.authentication.userName).then(function(results) {
$scope.empleadoLegalizar = results.data;
}, function() { //error
console.log('error al consultar');
});
dashboardService.getEmpleadoPdtLegalizarSub(accesoService.authentication.userName).then(function(results) {
$scope.PdtLegalizarSub = results.data;
}, function() {
console.log('Error al traer los pdtes por Legalizar');
});
dashboardService.getLegPdtAutorizar(accesoService.authentication.userName).then(function(result) {
$scope.LegPdtAutorizar = result.data;
}, function(error) {
console.log(error);
});
dashboardService.getLegPdtAprobar(accesoService.authentication.userName).then(function(result) {
$scope.LegPdtAprobar = result.data;
}, function(error) {
console.log(error);
});
dashboardService.getEmpleado(accesoService.authentication.userName).then(function(result) {
$scope.Nombre = result.data.Nombre;
}, function(error) {
if (!angular.isUndefined(error)) {
angular.forEach(error.data.ModelState.Model, function(errores) {
notificaService.error(errores);
});
}
});
dashboardService.solicitudesActivasEmpleado(accesoService.authentication.userName).then(function(result) {
$scope.solActivas = result.data;
});
/*$scope.solicitudesActivasEmpleado = function(){
console.log('entro activas');
$scope.pagActual = 0;
$scope.pageZise = 3;
$q.all([
dashboardService.solicitudesActivasEmpleado(accesoService.authentication.userName)
]).then(function(results){
$scope.solActivas = results[0].data;
$scope.numPaginas = function(){
return Math.ceil($scope.solActivas.length / $scope.pageZise);
};
}, function(error){
console.log(error);
});
};*/
$scope.CambiaEstadoSol = function(id, documento, estado) {
var parametros = '?id=' + id + '&documento=' + documento + '&estado=' + estado + '&funLog=' + accesoService.authentication.userName;
dashboardService.putCambiaEstadoSol(parametros).then(function() { //results
$location.path('#/dashboard'); //Lo hago para que me actualice la lista de pendientes x aprobar
if (estado === 'A') {
notificaService.success('Solicitud Aprobada Exitosamente');
}
if (estado === 'T') {
notificaService.success('Solicitud Autorizada Exitosamente');
/*if (documento==='L') {
//legalizacionService.postLegalizarAndres
}*/
}
if (estado === 'N') {
notificaService.success('Solicitud Anulada Exitosamente');
}
}, function(error) {
error.data.ModelState.Model.forEach(function(data) {
notificaService.error(data);
});
});
};
$scope.VerSolicitud = function(id) {
$location.path('/solicitud/' + id);
};
$scope.LegalizarSolicitud = function(id) {
$location.path('/legalizacion/' + id + '/' + 'L');
};
$scope.CambiaEstadoLeg = function(id) {
$location.path('/legalizacion/' + id + '/' + 'A');
};
}
]);
angular.module('gastosDeViaje').filter('paginacion', function() {
return function(input, start) {
if (!input || !input.length) {
return;
}
start = +start;
return input.slice(start);
};
});
})();
The problem seems to be on $('.dropdown-button').dropdown(); that is called from template in <li ng-repeat="item in menus" ng-init="$last && rebindDropDowns()"... but I can't simulate this issue.
It happens because ng-init is running before render html on DOM. Then when you apply jQuery plugin, the element doesn't exists yet.
By the way, using jQuery inside controller is not a good idea at all.
UPDATE 1
Try using a directive to initialize jQuery plugins like so:
angular.module('gastosDeViaje').directive('dropdownButton',
function() {
return {
restrict: 'EAC',
link: function($scope, element, attrs, controller) {
jQuery(element).dropdown();
}
};
}
);
This will apply directive for the class .dropdown-button.
I made this change and it worked: D
<div ng-controller="dashboardController" class="nav-wrapper">
<ul ng-init="menuApp()">
<li ng-repeat="item in menus" class="{{item.Submenu.length ? 'dropdown-button' : ''}}" ng-bind-html="item.Nombre" data-activates="{{item.Submenu.length ? 'administracion' : ''}}">
{{item.Opcion}}
<ul ng-if="item.Submenu.length>0" id="administracion" class="dropdown-content">
<li ng-repeat="subItem in item.Submenu" ng-init="$last && rebindDropDowns()">
<a ng-href="{{subItem.Nombre}}">{{subItem.Descripcion}}</a>
</li>
</ul></li></ul></div>

Categories