Error: .$save is not a function (AngularJS) - javascript

The non-GET instance action $save doesn't work in my example. I always get the Error, that $save is not a function. The problem is, I don't know where I have to define the $scope.example = new Resource();, because in my example I'm using 2 Controllers. One for the table list with objects and the other one for my modal window, where you can take CRUD operations. The CRUD operations are defined in an angular service.
The code is structured as follows:
Servie of Resource:
...
return {
name: $resource(baseUrl + '/api/name/:Id', {
Id: '#Id'
}, {
'update': {
method: 'PUT'
}
}),
...
Service of CRUD:
...
return {
create: function (newName) {
return newName.$save();
},
...
Ctrl of modal window:
$scope.selected = new resService.name();
$scope.createItem = function (newName) {
CrudService.create(newName).then(
function () {
$scope.dataSuccess = 'Person created.';
$scope.newName = null;
},
function (err) {
$scope.dataError = err.data.ModelState;
});
}
}
$scope.form = [{
label: 'Firstname',
fieldType: 'text',
name: 'Fname',
id: 'fname-id',
propertyName: 'fname',
disabled: false,
pattern: /^[a-zA-Z]{4}[a-zA-Z]*/,
required: true,
errRequired: 'Firstname is required.',
errPattern: 'Firstname has at least 4 letters.'
},
...];
The view with form:
<form class="form-horizontal" name="editForm" novalidate>
<div class="form-group-sm has-feedback" ng-repeat="elem in form" ng-class="{ 'has-error' : hasError(editForm, elem.name), 'has-success' : hasSuccess(editForm, elem.name) }">
<label class="control-label" for="{{elem.id}}">{{elem.label}}</label>
<input type="{{elem.fieldType}}"
class="form-control"
placeholder="{{elem.label}}"
name="{{elem.name}}"
id="{{elem.id}}"
ng-model="selected[elem.propertyName]"
ng-disabled="{{elem.disabled}}"
ng-pattern="elem.pattern"
ng-required="{{elem.required}}"
/>
<p class="help-block" ng-if="elem.errRequired" ng-show="editForm[elem.name].$error.required && editForm[elem.name].$touched">{{elem.errRequired}}</p>
<p class="help-block" ng-if="elem.errPattern" ng-show="editForm[elem.name].$error.pattern">{{elem.errPattern}}</p>
EDIT:
I'm getting a new Error. The console tells, that I have to use track by expression. But I was trying to use the form view without generating and then works. But I need the generated form view (the example view above).
Error Message:
Error: ngRepeat:dupes
Duplicate Key in Repeater
Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys.

If you wan't to create a new object you need the choose the service between the Services choice (factory, service, providers).
The difference between a factory and a service, is about syntax. Just syntax.
.factory(function(){
//Private variables and functions
var x = "ez";
function getX(){
return x;
}
//Public functions (or variables)
return {
a : "test",
getA : function(){
return a;
}
}
})
//Service example
.service(function(){
//Handled by Angular:
//new() is used to create a new object
//Private functions and variables
var x = "test";
function getX(){
return x;
}
//Public funcitons (and variables)
this.a = function(){
"test";
};
this.getA = function(){
return a;
};
//Handeled by AngularJS
//return this;
});
Everything that is returned in the factory is available.
The service automaticaly creates a new object when calling it, which makes available the object ("this")
Calling a service or a factory remains the same:
var a = service.getA();
var a = factory.getA();
EDIT
Notice also that you can decide if your promise is going to the next error or success call.
Just as an exmaple:
xhr()
.then(success1, error1)
.then(success2, error2)
.then(success3, error3)
...
success and error are all callback functions.
By using $q you can go to the next success or error, wathever the callback.
QUESTION CODE
. factory ( 'YourFacotry' , [ '$resource' ,
function ( $resource ) {
return $resource ( '/api/note/:id' , { id : '#id' },
{
markAsDone :
{
url : '/api/note/:id/done' ,
method : 'POST' ,
isArray : true
}
});
}]);
Ctrl of modal window:
$scope.createItem = function () { //Forgot $scope here!
CrudService.query().then(
function () {
$scope.dataSuccess = 'Person created';
$scope.newName = null;
},
function (err) {
$scope.dataError = err.data.ModelState;
});
}
}

Related

Angular, queuing ng-init

Is it possible queuing ng-init?
Generally, in first init I want to add JSON file to prototype vars (array) and in another init depending on the params I want to skip getJsonData() or add other JSON file to prototype.
function init(param) {
console.log("startInit");
// big JSON file
var promise = getJSON(param);
return promise.then( function() {
//some func
console.log("finish");
return true;
});
};
function getJSON(param) {
var deferred = $q.defer();
console.log("startInitDataInner");
someService.getJsonData(param).then(function(data) {
// some code
console.log("endInitDataInner");
deferred.resolve();
}, function(error) {
deferred.reject();
});
return deferred.promise;
};
in view ng-init
ng-init="init(param)"
ng-init="init(param)"
// ...
and log:
startInit
startInitDataInner
startInit
startInitDataInner
endInitDataInner
finish
endInitDataInner
finish
//..
Edit:
Generally, I want to create something like plugin in jQuery. I have this code:
<div ng-controller="parentController as parent">
<div ng-controller="childController as child" ng-init="child.init(parent.data)"></div>
</div>
<div ng-controller="parentController as parent">
<div ng-controller="childController as child" ng-init="child.init(parent.data2)"></div>
</div>
and configurable part by user:
angular.module('myApp').controller('parentController', ['$scope', function($scope) {
this.data = {
config: {
lang: "en",
title: "title"
}
};
this.data2 = {
config: {
lang: "pl",
title: "title2"
}
};
}]);
ng-init update api:
angular.extend(this, parent.data);
Do you have any ideas how I should do it differently?
Well, if you are working with angular, you use controllers. What is controller itslfmin general meaning? Right, its a constructor function. The main word here is function. What does function in general? Run the code inside.
So, just place your initial logic at the beggining of controller code (but without wrapping it as a separate function) and it will run just in time your controller will be resolved by angular resolver.
var controller = function () {
// vars, costs, etc.
console.log("startInit");
// big JSON file
var promise = getJSON(param);
return promise.then( function() {
//some func
console.log("finish");
return true;
});
};

ng-show - using a service as a scope parameter

I'm writing an angular 1.5.0-rc0 application using bootstrap for a nav bar component.
I want to show the user an added items to his navigation bar if his user group id is 1.
first I created a service:
app.factory('UserService', function() {
return {
userGroupId : null
};
});
I created the nav bar as a directive, so i included it in the main html file
<nav-bar></nav-bar>
and the nav-bar directive code:
(function () {
angular.module('myalcoholist').directive('navBar', function () {
return {
restrict: 'E',
templateUrl: 'views/nav.html',
controller: ['$scope','$auth', 'UserService',function ($scope,$auth,UserService) {
$scope.user=UserService;
$scope.isAuthenticated = function()
{
return $auth.isAuthenticated();
};
}]
}
});
})();
as you can see I set $scope.user as the returned object from UserService.
in my login controller, after a successful login I set the userGroupId.
angular.module('myalcoholist').controller('LoginController',['$scope','$auth','$location', 'toastr','UserService',function ($scope,$auth,$location,toastr,UserService) {
$scope.authenticate = function (provider) {
$auth.authenticate(provider).then(function (data) {
var accessToken = data.data.token;
apiKey=accessToken;
UserService.userGroupId=data.data.user_group_id;
...
now.. my nav-bar template file is as the following code:
<li ng-show="user.userGroupId == 1">
Admin Drinks
</li>
even after the authentication, when I uset userGroupId to 1 the element is still not shown.
any ideas?
update
I debugged and noticed that UserService.userGroupId is still null. so
I changed the UserService to have the following code:
app.factory('UserService', function() {
var user = {userGroupId:null};
return {
setUserGroupId: function (userGroupId) {
user.userGroupId=setUserGroupId;
},
getUserGroupId: function () {
return user.userGroupId;
}
};
});
in my LoginController I now try to execute setUserGroupId:
angular.module('myalcoholist').controller('LoginController',['$scope','$auth','$location', 'toastr','UserService',function ($scope,$auth,$location,toastr,UserService) {
$scope.authenticate = function (provider) {
$auth.authenticate(provider).then(function (data) {
var accessToken = data.data.token;
apiKey=accessToken;
UserService.setUserGroupId(data.data.user_group_id);
...
when I debug i see that userService is an object with two functions as I defined, but when the javascript chrome debugger tries to execute this line:
UserService.setUserGroupId(data.data.user_group_id);
I get the following error:
ReferenceError: setUserGroupId is not defined
at Object.setUserGroupId (app.js:21)
at login-controller.js:12
at angular.js:15287
at m.$eval (angular.js:16554)
at m.$digest (angular.js:16372)
at m.$apply (angular.js:16662)
at g (angular.js:11033)
at t (angular.js:11231)
at XMLHttpRequest.v.onload (angular.js:11172)
I have created a fiddle showcasing your requirement (as close as possible), and it seems to work fine.
http://jsfiddle.net/HB7LU/21493/
My guess is that you aren't actually setting the value when you think you are, and will likely require some debugging. Here is the code for brevity.
HTML
<div ng-controller="MyCtrl">
<div ng-click="clicked()">
Click ME, {{user.value}}!
</div>
<test-dir></test-dir>
</div>
JS
angular.module('myApp',[])
.service('TestService', function(){
return {
value: 2
};
})
.directive('testDir', function(){
return {
restrict: 'E',
template: '<div ng-show="user.value === 1">Here is some text</div><div>Some more always showing</div>',
controller: function ($scope, TestService) {
$scope.user = TestService;
}
};
})
.controller('MyCtrl', function($scope, TestService){
$scope.user = TestService;
$scope.clicked = function(){
TestService.value = 1;
};
});

Angular Directive Element dynamic Template fields with its updated model value from controller?

I have <superhero> directive which has two directive
web-buttons to take of the form validation and post the updated
ngModel value to respective controller
fieldMap directive to generate the dynamic fields by object we are passing from respective controller
Here is the example which i have worked
directive attribute called saveFormFn will tell the button to call which function to invoked using enter attribute directive.
For example. After click save button it will call the function 'Ctrl1saveFormFn' from controller Ctrl1 .This function will make ajax post to save the form fields.
After updating the text fields with some content and click save,I have passed the current scope of the directive to respective controller (see console log). i could not get the updated fielddata value from current Scope.
$scope.Ctrl1saveFormFn = function(item){
_.each(item,function(currentScope){
console.log(currentScope)
// here i want to collect the form data with updated fielddata values
})
}
I am beginner.Am i on right path? Please advice
I've re-written your code because it was pretty hard to understand.
I would do it like this:
Use ng-include to load the template of your buttons. That's loading the control buttons edit and save.
Save your data in a variable in the superhero directive. Maybe it would be even better to store it in a separate service/factory.
Create a directive customForm that will create a form based on the supplied model that you're passing to its scope.
The main application logic is in the superhero directive because it is adding the controls save/edit to the DOM. If saving/editing is not only related to the superhero it would be better to do it in your main controller.
Please have a look at the demo below or in this jsfiddle.
angular.module('demoApp', [])
.directive('superhero', Superhero)
.directive('customForm', CustomForm)
.controller('mainController', MainController);
function Superhero() {
return {
restrict: 'E',
scope: {
formModel: "=",
},
template: '<div class="hero"><div ng-include="\'web-buttons.html\'"></div><custom-form model="formModel"></custom-form></div>',
controllerAs: 'superHeroCtrl',
controller: function ($scope) {
var self = this;
console.log('controller directive');
angular.extend(this, {
abilities: [],
editMode: false,
addStrength: function (data) {
self.abilities.push(data);
},
getStrength: function () {
return self.abilities;
},
showSave: function() {
self.editMode = true;
$scope.formModel.editMode = true;
},
hideSave: function() {
self.editMode = false;
$scope.formModel.editMode = false;
},
save: function() {
self.addStrength('can fly');
console.log(self.getStrength());
console.log('saving data now of form now...', $scope.formModel.data);
alert('saving data of form now: ' + self.getStrength()[0] + ' - ' + JSON.stringify( $scope.formModel.data, null, 2));
self.hideSave();
}
});
}
}
}
function CustomForm() {
return {
restrict: 'EA',
scope: {
model: '='
},
template: '<div ng-if="model.editMode" ng-repeat="formElement in model.fields" ng-include="formElement.template.url"></div>'
}
}
function MainController() {
this.normalForm = {
editMode: false,
data: {
},
fields: {
'NAME':{
template: {
url: 'customForms/text.html',
type: 'edit' // not sure for what it is needed
},
label: 'First name',
id: "NAME",
placeholder : "First Name",
fieldData: "NAME",
key : 'first_name'
},
'LNAME': {
template: {
url: 'customForms/text.html',
type: 'edit' // not sure for what it is needed
},
label: "Last Name",
placeholder : "Last Name",
id: "LNAME",
key : 'last_name'
}
}
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="mainController as mainCtrl">
<script type="text/ng-template" id="customForms/text.html">
<label for="{{formElement.id}}">{{formElement.label}}</label>
<input ng-model="model.data[formElement.key]" placeholder="{{formElement.placeholder}}" id="formElement.id"/>
</script>
<script type="text/ng-template" id="web-buttons.html">
<button ng-click="superHeroCtrl.showSave()" ng-if="!superHeroCtrl.editMode">edit</button>
<button ng-if="superHeroCtrl.editMode" ng-click="superHeroCtrl.save()">save</button>
</script>
<superhero form-model="mainCtrl.normalForm"></superhero>
<h3>debug output:</h3>
<pre>
{{mainCtrl.normalForm |json}}
</pre>
</div>

Angular JS, how to pass URL parameters to $resouce in angularJS?

Hi I have a simple controller where it passes unique integers into my url, but Im running to many issues. I need to change this "4401" dynamically from my controller.
the url Im trying to reach:
https://itunes.apple.com/us/rss/topmovies/limit=50/genre=4401/json
app.factory('classic',function ($resource) {
return $resource('https://itunes.apple.com/us/rss/topmovies/limit=50/genre=:id/json', {
get: {
method: 'JSONP',
id: '#id'
}
});
});
and here is my controller
app.controller('TestCrtl', function ($scope, classic) {
init();
function init(id) {
$scope.movies = classic.get(id);
}
$scope.classicMovies = function(){
var id = "4403";
init(id);
}
$scope.anctionMovies = function(){
var id = "4404";
init(id);
}
});
The error Im getting
Uncaught SyntaxError: Unexpected token :
any help would be highly appreciated.
<div class="col-sm-4">
<button type="button" data-ng-click="actionMovies()" class="btn btn-default">Action</button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-default">Scary</button>
</div>
I believe this is the correct way to implement parameters when using a resource factory:
app.factory('movieService',function ($resource) {
return $resource('https://itunes.apple.com/us/rss/topmovies/limit=50/genre=:id/json', {id: '#id'}, {
query: { method: 'GET', isArray:true, params: {id: '#id'} }
});
});
This can be simplified to:
app.factory('movieService',function ($resource) {
return $resource('https://itunes.apple.com/us/rss/topmovies/limit=50/genre=:id/json', {id: '#id'});
});
To call this get method you would need to do the following. Note the parameters that are used in the get method.
app.controller('TestCrtl', function ($scope, movieService) {
$scope.classicMovies = function(){
movieService.query({id: 4403}, function(result){
$scope.movies = result;
});
}
$scope.anctionMovies = function(){
movieService.query({id: 4404}, function(result){
$scope.movies = result;
});
}
});
Additionally, it should be noted that the resource method call is going to return a promise. You can either set it from the return value of the get method, like you did above (The status of the promise isn't guaranteed), or you can set it in the callback, which guarantees that the promise is resolved.
Try this:
app.factory('classic',function ($resource) {
return $resource('https://itunes.apple.com/us/rss/topmovies/limit=50/genre=:id/json', {
get: {
method: 'JSONP',
id: '#id'
}
});
});
And in controller change to :
$scope.movies = classic.get(id);

AngularJS Dynamic Filter Configuration fail to resolve

I'm a newbie to AngularJS with some fair knowledge with KnockoutJS also.
I'm trying to implement a search feature on 'products' in my ViewModel that is configurable by the end user by combining..
Search by 'name' of product
Search by 'tags' of product
in combination with search operations
CONTAINS
STARTS WITH
EQUALS
I believe you understood the functionality I am trying to build up.
The following is the ViewModel I'm using.
var InstantSearchController = function ($scope) {
var self = this;
$scope.filtersAvailable = [
{
displayText: 'Tag',
filterMethod: 'tagFilter',
description: 'Filter by Tags'
},
{
displayText: 'Description',
filterMethod: 'descriptionFilter',
description: 'Filter by description'
}
];
$scope.selectedFilter = $scope.filtersAvailable[1];
$scope.filterBehaviorsAvailable = [
{
displayText: 'CONTAINS',
regexPrefix: '',
regexPostfix: ''
},
{
displayText: 'STARTS WITH',
regexPrefix: '^',
regexPostfix: ''
},
{
displayText: 'EQUALS',
regexPrefix: '^',
regexPostfix: '$'
}
];
$scope.selectedFilterBehavior = $scope.filterBehaviorsAvailable[0];
$scope.products = [
{
name: 'Household Product',
description: 'Description household',
tags: ['personal', 'home']
},
{
name: 'Office product',
description: 'Business equipments',
tags: ['office', 'operations', 'business']
},
{
name: 'Misc products',
description: 'Uncategorized items',
tags: ['noclass']
}
];
}
Now, the following is my filters list.
var app = angular.module('InstantSearchModule', []);
//FILTERS BEGIN
app.filter('descriptionFilter', function () {
var filterFunction = function (data, filterBy) {
if (filterBy == null || filterBy === '')
return data;
var filtered = [];
var regExp = new RegExp(filterBy, 'gi');
angular.forEach(data, function (item) {
if (item.description.match(regExp))
filtered.push(item);
});
return filtered;
};
return filterFunction;
});
app.filter('tagFilter', function () {
var tagFilter = function (data, filterBy) {
if (filterBy == null || filterBy === '')
return data;
var filtered = [];
var regExp = new RegExp('^' + filterBy, 'gi');
debugger;
angular.forEach(data, function (item) {
var isMatching = false;
angular.forEach(item.tags, function (t) {
isMatching = isMatching || (t.match(regExp) != null);
});
if (isMatching)
filtered.push(item);
});
return filtered;
};
return tagFilter;
});
// FILTERS END
I have created a working part to configure search criteria including the 'filterString'(in a textbox), search operand[tags or description](with a select list) and a search mode[starts with / contains / equals](with another select list). Both of the filters are working fine if I specify the filter functions (tagFilter or descriptionFilter) directly in AngularJS directives as follows [JSFiddle Here].
<div data-ng-repeat="p in products|tagFilter:filterString|orderBy:'description.length'">
<h4 style="margin-bottom: 5px">{{$index+1}}. {{p.name}}</h4>
<div>
{{p.description}}
<button data-ng-repeat="t in p.tags|orderBy:'toString()'">{{t}}</button>
</div>
</div>
I was expecting the following to work for me as {{selectedFilter.filterMethod}} is rendering the value successfully, but is showing an error. Please see the HTML I tried to use for it.JSFiddle Here
<div data-ng-repeat="p in products|{{selectedFilter.filterMethod}}:filterString|orderBy:'description.length'">
<h4 style="margin-bottom: 5px">{{$index+1}}. {{p.name}}</h4>
<div>
{{p.description}}
<button data-ng-repeat="t in p.tags|orderBy:'toString()'">{{t}}</button>
</div>
</div>
I have attached the error I'm receiving in Google Chrome developer tools along with the resultant HTML to the subject. Please see below.
As you can see in the HTML, the filter method is not resolved and so, its not working for me. Do you guys have an advice what I am doing wrong?
If I understand it correctly all you need is a way to dynamically change filters. Everything else seems to be working.
I dont think you can use the syntax you are trying to use but you can make a third filter that injects the two others and chooses the right one depending on the parameters you send in.
New filter:
app.filter('multiFilter', function (descriptionFilterFilter, tagFilterFilter) {
var filterFunction = function (data, filterBy, filterRegExp, selectedFilter) {
if(selectedFilter.displayText === 'Description') {
return descriptionFilterFilter(data, filterBy, filterRegExp);
}
else {
return tagFilterFilter(data, filterBy, filterRegExp);
}
};
return filterFunction;
});
As you can see it also takes the filterRegExp and the selectedFilter as parameters. I also changed your old filters to take selectedFilter as a parameter.
Also notice that you have to append "Filter" to the filter name in order to inject it.
You call the new filter like this
multiFilter:filterString:filterRegExp:selectedFilter
So the div could loke something like this
<div data-ng-repeat="p in products|multiFilter:filterString:filterRegExp:selectedFilter|orderBy:'description.length'"
title="{{selectedFilter.filterMethod}}">
<h4 style="margin-bottom: 5px">{{$index+1}}. {{p.name}}</h4>
<div>
I made a working fork of your fiddle
Your fiddle is not working and has other error but, the reason filters are not loading is that you have used global controller function and not registered with your app module for the injection to work. Your filter belong to module InstantSearchModule but you controller does not.
Try the module registration syntax
app.controller('InstantSearchController',function($scope) {
});
see the Angular guide on controller https://code.angularjs.org/1.2.15/docs/guide/controller
Update: As it turns out the issue is not with dependency injection. It is because you cannot use expression to dynamically change filter. When i set to fixed filter it works fine
<div data-ng-repeat="p in products|descriptionFilter:filterString|orderBy:'description.length'"
title="{{selectedFilter.filterMethod}}">
You would have to either combine then or find a way to do select filtering.
See my fix here
http://jsfiddle.net/cmyworld/pW9EZ/1/

Categories