ng-repeat doesn't auto refresh after save - angularjs

I am trying to post some data via save but cannot see the data in the browser unless i refresh, the todo.id is showing straight away but not the todo.name
<body ng-controller="TodoCtrl">
<div ng-repeat="todo in Todos.record">
<div>{{todo.id}} : {{todo.name }}</div>
</div>
<div>
<input ng-model="todo.name" />
<button ng-click="addItem()">Add Item</button>
</div>
</body>
var app = angular.module("myApp",['ngResource']);
app.factory("Todo",function($resource){
return $resource(
"http://localhost/rest/motors/users?app_name=motors",
{},
{
query: {method: 'GET',isArray: true},
get: {method: 'GET'},
save:{method:'POST'}
}
)
})
app.controller("TodoCtrl", function ($scope, Todo) {
"use strict";
$scope.Todos = Todo.get();
$scope.addItem = function(){
Todo.save($scope.todo, function(data){
$scope.Todos.record.push(data);
$scope.todo={};
});
}
})

If that code sample is representative of your real code, it's likely a problem that the "input" field that references "todo.name" is OUTSIDE of the ng-repeat loop, so that is defining a model property outside of your "Todos.record" list.

adding &fields=* in the api url solved the issue. eg changed
"http://myexample.com/rest/motors/users?app_name=motors"
to
"http://myexample.com/rest/motors/users?app_name=motors&fields=*"
Thanks for help.

Related

making a url with the $http using routing params error

Below is the link of my file. I was unable to generate a url from the existing url generated from $http, by using $parent.$index and $index as ids from routing, please help: Plunker
I have applied the same kind of functionality to another application it worked have a look at this Plunker
Inside the loadSingleMatch() function error in updating the url inside the $http
error image:-
Code
app.controller("selfController", ['$http', '$routeParams',
function($http, $routeParams) {
//create a context
var main = this;
this.parentId = $routeParams.parent;
this.childId = $routeParams.child;
console.log(this.parentId);
console.log(this.childId);
this.urlOne = "https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.json";
this.urlTwo = "https://raw.githubusercontent.com/openfootball/football.json/master/2016-17/en.1.json";
this.loadSingleMatch = function() {
$http({
method: 'GET',
url: main.urlOne + '/' + main.parentId + '/' + main.childId
}).then(function successCallback(response) {
main.matchData = response.data.rounds[main.parentId].matches[main.childId];
console.log(main.matchData);
}, function errorCallback(response) {
console.log(response);
});
}
}
]);
The a tag should be inside the second ng-repeat:
<div class="w3-row w3-hover-shadow w3-hover-border-black w3-border w3-white w3-padding-16" ng-repeat="x in matchDay.matches">
<a ng-href="#/indiTeam/{{$parent.$index}}/{{$index}}" >
<div class="w3-small">
<div class="w3-col s6 ">
{{x.team1.code}} vs {{x.team2.code}}
</div>
<div class="w3-col s6">
<div class="w3-padding-small">
{{ x.date | date: 'shortDate'}}
({{$parent.$index}} {{$index}})
</div>
</div>
</div>
</div>
</a>
</div>
See modified plunker:
https://plnkr.co/edit/PeqUHIZVC0HsqdjLkdOo?p=preview
Finally found out the answer to my question
the url inside the $http should not be changed only the response inside of it needs to be changed
the url: main.urlOne is the change that bought the output as expected

Split in Angular JS

Here is my code below:
vm.getid = function(){
$http({
method: 'GET',
url: 'api.json',
})
.then(function successCallback(data) {
$scope.id = data.data;
console.log($scope.id);
$scope.split = $scope.id.split('/');
}, function errorCallback(response) {
console.log(response);
console.log('error');
});
};
And here is my html, but it does not work :
<div ng-repeat="s in split">
{{s}}
</div>
Plunker : http://plnkr.co/edit/g1t4pludTTIAJYKTToCK?p=preview
I want to use ng-repeat $scope.split
Thanks!
$scope.id is a list.
What you want to achieve is to get list of lists
The easy way to render it, to use 2 ng-repeats
What about:
<div ng-repeat="i in id">
<div ng-repeat="s in i.split('/')">
{{s}}
</div>
</div>
Demo 1
Or create split list as:
$scope.split = [];
angular.forEach($scope.id, function (item) {
$scope.split.push(item.split('/'));
});
so HTML will look like:
<div ng-repeat="sp in split">
<div ng-repeat="s in sp">
sub: {{s}}
</div>
</div>
Demo 2
printing out id you can see it is an array, not a string
["/big_big_package","/door/cooler","/door/chair","/door","/lets/go/deeper/than/this","/lets/go/deeper","/low"]
and trying to split it gives the following error in console
$scope.id.split is not a function
you can't split an array, you probably want to split each element in the array

ng-click inside ng-repeat doesnt work

I have html which looks like one below, I have 2x ng-click in whole code in both situation I call same function. Both functions are in same controller.
<div class="tagselect tagselect--frameless">
<div class="combobox__body combobox__body--open combobox__body--frameless" ng-show="focus">
<ul class="list-unstyled">
<li class="combobox__item" ng-repeat="pos in listCtrl.positions | filter:query as results"
ng-click="listCtrl.choosePosition(pos)">{{pos.name}}
</li>
</ul>
</div>
</div>
<div class="col-md-2 no-padding">
<button type="button" class="btn btn-success" ng-click="listCtrl.chosenPositions(789456)">Add</button>
</div>
controller looks like:
myApp.controller('ListCtrl', ['$scope', '$cookies', '$http', function ($scope, $cookies, $http) {
var listCtrl = {
candidates: [],
positions: [],
chosenPositions: [],
init: function () {
listCtrl.getCandidates();
listCtrl.getPositions();
},
getCandidates: function () {
$http.get('candidates.json').then(function (res) {
listCtrl.candidates = res.data;
});
},
getPositions: function () {
$http.get('positions.json').then(function (res) {
listCtrl.positions = res.data;
});
},
choosePosition: function (position) {
console.log(position);
}
};
listCtrl.init();
$scope.listCtrl = listCtrl;
}]);
I double check for missspells and make sure its not because of function (I create a new one with simple console log).
Problem is that button click correctly call function but ng-repeat <li ng-click=""> doesnt do anything. I read in angular documentation that ng-repeat create new scope but this should be still okey in my opinion as soon as I use reference to object listCtrlchoosePosition()
Can someone tell me what I am doing wrong?
Thanks
EDIT: Plunker example:
http://plnkr.co/edit/ooUQA2n1Vyj8RZtsQ1Pj?p=preview
ng-blur is doing something weird, so I'm going to suggest you to change the $scope.focus value from the ListCtrl instead of using the ng-blur.
html file
<!-- more html code -->
<!-- input without ng-blur directive -->
<input class="tagselect__input" placeholder="Position" ng-focus="focus=true" ng-model="query">
<!-- more html code -->
<li class="combobox__item" ng-repeat="pos in listCtrl.positions | filter:query as results" ng-click="listCtrl.choosePosition(pos)">{{pos.name}}
<!-- more html code -->
js file
// more code goes here.
choosePosition: function (position) {
//alert('Going to choosen position');
//$scope.query = position.name;
$scope.focus = false; // Hide div options from here.
// rest of your code.
},
// more code goes here.
Working in this plunkr

refactoring "factories" into a $resource

Hi I have converted a previous function for editing records in an api into the following resource:
app.factory("Wine", function($resource){
return $resource("http://greatwines.8000.com/wines:id", {
//id as a variable
id: "#id"
},
{
update: {
method: "PUT"
}
});
});
I now want to use this by triggering a form with the "wine" records to edit with the following CTA inside the wine ng-repeat for each wine:
Edit Wine
In my controller I pass the "Wine" resource:
app.controller("editWineCtrl", function ($scope, $http, $routeParams, Wine, $location){
Wine.get({ id: $routeParams.id }, function(wine){
$scope.wine = wine;
});
...
However, in spite of the form URL returning the ID:
http://greatwines.8000.com/#/wines/1323
None of the fields i.e. :
div class="margin-top-20">
<input type="text" class="form-control" ng-model="wine.year" />
</div>
<div class="bold margin-top-20">
Grapes
</div>
<div class="margin-top-20">
<input type="text" class="form-control" ng-model="wine.grapes" />
</div>
Are being populated. Am I using the resource int he correct way?
There is a typo in url
wines:id
It should be
wines/:id

Very simple ng-model watch not working

Here is the jsfiddle.
http://jsfiddle.net/CLcfC/
code
var app = angular.module('app',['']);
app.controller('TestCtrl',function($scope){
$scope.text = 'Change Me';
$scope.$watch('text',function(){
alert('Changed !');
});
})
HTML
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="TestCtrl">
<input type="text" ng-model='text'/>
<span>{{text}}</span>
</div>
</div>
I am not able to see the change in $scope.text. Please help.
This is so easy but what am I missing?
Change the module creation to this, make sure you don't put a empty string in the []. (Obvious the empty string is not a module that can be injected.)
var app = angular.module('app', []);
Demo: http://jsfiddle.net/MWa66/
Your JavaScript file loads after the AngularJS initialization and that's why it fails to find your module. In order to fix it change the initialization to a manual initialization.
First change your HTML and remove the ng-app directive:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div id="appRoot">
<div ng-controller="TestCtrl">
<input type="text" ng-model='text'/>
<span>{{text}}</span>
</div>
</div>
Then go to your JavaScript and use angular.bootstrap method to manually attach your module:
var app = angular.module('app',[]);
app.controller('TestCtrl',function($scope){
$scope.text = 'Change Me';
$scope.$watch('text',function(){
alert('Changed !');
});
});
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById('appRoot'), ['app']);
});
You can find more help on manual AngularJS initialization here.
Thank you! I solved this annoying thing!
The solution that worked for me was that I use angular UI router and there I had used the following code
.state('app.monimes', {
url: "/monimes",
views: {
'menuContent' :{
templateUrl: "templates/monimes.html",
controller: 'sampleCtrl'
}
}
})
so then in the controller I had
/***
*
*Controller for tests..
*/
.controller('sampleCtrl',['$scope','sampleService', function($scope, $sampleService) {
$scope.username="em";
// Watch for changes on the username property.
// If there is a change, run the function
$scope.$watch('username', function(newUsername) {
// uses the $http service to call the GitHub API
// //log it
$scope.log(newUsername);
// and returns the resulting promise
$sampleService.events(newUsername)
.success(function(data, status, headers) {
// the success function wraps the response in data
// so we need to call data.data to fetch the raw data
$scope.events = data.data;
});
},true);
}
]);
and in the view I had
<div>
<label for="username">Type in a GitHub username</label>
<input type="text" ng-model="username" placeholder="Enter a GitHub username, like a user" />
<pre ng-show="username">{{ events }}</pre>
</div>
but that didn't work.
so I added ng-controller="sampleCtrl"
to the div and now it works :D
so that means that the view is loaded after the controller loads and the watcher doesn't get added to the watching variable.

Resources