Can not get alert in service of angularjs - javascript

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="canerApp" ng-controller="canerCtrl">
<button ng-click="click()">
Button click
</button>
<p ng-show="isClicked">
name=
<input type="text" ng-model="caner.name">
<br> surnanme=
<input type="text" ng-model="caner.surname">
<br> age
<select ng-model="caner.age"
ng-options=" person.age as person.age for person in peole" >
</select>
<br> Welcome Message: {{ caner.name + " " + caner.surname+" "+caner.age}}
</p>
</div>
<script type="text/javascript">
var app = angular.module('canerApp', []);
app.controller('canerCtrl', function($scope,$window) {
$window.alert("ctrl");
$scope.caner = {
name: "caner",
surname: "aydin",
age: "22",
};
$scope.peole = [{
age: 1,
name: 'Bob'
}, {
age: 2,
name: 'Alice'
}, {
age: 3,
name: 'Steve'
}];
$scope.isClicked = true;
$scope.click = function(User) {
$window.alert("ctrl fun");
$scope.isClicked = !$scope.isClicked;
$scope.caner.name = User.save;
};
});
app
.factory('User', function($http,$window) { // injectables go here
var backendUrl = "http://localhost:3000";
$window.alert("service");
var service = {
// our factory definition
user: {},
setName: function(newName) {
service.user['name'] = newName;
},
setEmail: function(newEmail) {
service.user['email'] = newEmail;
},
save: function() { $window.alert("service saave");
return $http.post(backendUrl + '/users', {
user: service.user
});
}
};
return service;
});
</script>
</body>
</html>
this is my code. it can be seen here
http://plnkr.co/edit/gP2NcC38JPsabQFacGkb?p=preview
i merged lots of codes. so there are some unnecessary codes.
What i want is when i click, i can see alert of
ctrl fun
and at firsst start, the alert of ctrl
but cant see the alerts in service.
controller should call service but it doesnot call.
the call is here in conroller
$scope.caner.name = User.save;
i tried also
User.save
or $scope.var = User.save
or
$scope.click = function(User,$scope) {
$window.alert("ctrl fun");
$scope.isClicked = !$scope.isClicked;
$scope.caner.name = User.save;
};
});
but this made worse because it did not even give alert of ctrl.
because probably he was using scope of controller.

You need to inject the User factory into your controller otherwise it will not get instantiated:
app.controller('canerCtrl', function($scope,$window,User) {...}
Regarding your service-call, make sure you do not define another User variable in your click-function. $scope and User are already available in the controller.
$scope.click = function() {
$scope.whatever = User.save();
}
However, keep in mind that you return a promise from your save-function, not a name.

Related

[$injector:nomod], [$injector:modulerr] error in Angular

I'm very new to angular js and following is my code
<script type="text/javascript" src="node_modules/angular/angular.min.js"></script>
<script type="text/javascript">
(function(angular){
var testAngular = angular.module('testAngular');
testAngular.controller = ("name_controller", function($scope) {console.log("hello");
$scope.name = {
firstName: "null",
lastName: "null",
setName: function(fname, lname) {
if(fname.trim != "") {
this.firstName = fname;
}
if(lname.trim()!="") {
this.lastName = lname;
}
},
getName: function() {
var name_object = $scope.name;
return name_object.firstName+" "+name_object.lastName;
}
};
});
})(window.angular);
</script>
<div ng-app="testAngular" ng-controller="name_controller">
Enter first name: <input type="text" ng-model="name.firstName"><br><br>
Enter last name: <input type="text" ng-model="name.lastName"><br>
<br>
You are entering: {{ name.firstName }}
</div>
Now when I'm trying to run this code I'm getting 2 errors in console as
[$injector:nomod]
and
[$injector:modulerr]
Any idea why exactly this is happening. Some post says I need to include the route module but I'm not using routing any where in my code.
Try to change:
testAngular.controller = ("name_controller", function($scope) {
to
testAngular.controller("name_controller", function($scope) {

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

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;
});
}
}

ng-click is not firing with factory class

I'm new in AngularJS. The following code is not executing after entering the username and password and clicking the login button. The login should execute the login method and populate person data binding object. Anybody knows why is not firing? Thanks.
Factory File
'use strict';
var usermodule = angular.module('retrieveBasicUserInfo', [])
.factory('basicUserInfo', function($http) {
var credentials = {
username: '',
password: ''
};
var person = "";
$http.defaults.useXDomain = true;
var getBasicUserInfo = function (credentials) {
var inputdata = { "Logon": credentials.username, "Pass": credentials.password};
$http.post('http://localhost:23034/api/wmsusers/login',JSON.stringify(inputdata),
{
headers: {
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).success(function (inputdata) {
person = inputdata[0];
});
};
return {
person: getBasicUserInfo
};
});
JavaScript File
'use strict';
var usermodule = angular.module('wms', ['retrieveBasicUserInfo'])
.controller('userAuthentication', ['basicUserInfo', function ($scope, basicUserInfo) {
$scope.credentials = {
username: '',
password: ''
};
$scope.login = function (credentials) {
console.log(credentials)
$scope.person = basicUserInfo.getBasicUserInfo(credentials);
}
}]);
HTML File
<div data-ng-controller="userAuthentication">
<div class="login-panel">
<p>Please complete the following form and click Login to continue:</p>
<form name="loginForm" data-ng-submit="login(credentials)" novalidate>
<label for="username">Username:</label>
<input type="text" id="username"
data-ng-model="credentials.username">
<label for="password">Password:</label>
<input type="password" id="password"
data-ng-model="credentials.password">
<button type="submit">Login</button>
</form>
</div>
<br>
<ul data-ng-model="$parent.person">
<li>Name: {{person.Name}}</li>
<li>Associate Id: {{person.Empid}}</li>
<li>Access Level: {{person.Access}}</li>
</ul>
Please see here http://jsbin.com/vaweja/2/edit.
Your factory returns object with person property and in your controller you are trying to reach getBasicUserInfo so chnage person to getBasicUserInfo. And you missed $scope in your controller definition
change that
return {
person: getBasicUserInfo
};
to
return {
getBasicUserInfo: getBasicUserInfo
};
and
var usermodule = angular.module('wms', ['retrieveBasicUserInfo'])
//and you missed $scope in line bellow after bracket
.controller('userAuthentication', ['$scope','basicUserInfo', function ($scope, basicUserInfo) {
$scope.credentials = {
username: '',
password: ''
};
$scope.login = function (credentials) {
console.log(credentials)
$scope.person = basicUserInfo.getBasicUserInfo(credentials);
}
}])
;

AngularJS Change a single scope item

A little difficult to explain,
we have worked through this sample
https://egghead.io/lessons/angularjs-understanding-isolate-scope
but its not quite matching what we are trying to achieve.
we have built a controller which simply sets myData
ClinicalNotesCtrl.controller('notesController', function notesController($scope, $http, $modal, $log) {
$scope.myData = { name: "Moroni", age: 50, result: "Sodium" };
$scope.changename = function (h) {
h.name = "Simon";
h.age = "34";
h.result = "This is a test";
}
});
Below is the directive called kid. This just simply prints out the value
Results.directive("kid", function () {
return {
restrict: "E",
// scope: { myValue: '=simon' },
// scope:{},
template: '<input type="text" ng-model="myData.name">{{myData.name}}' // '<div>{{$scope.timelineactivitydata}}</div>',
};
});
and finally this is the HTML page,
<kid simon="myData"></kid>
<label ng-click="changename(myData)">Change Name</label>
<kid simon="myData"></kid>
<label ng-click="changename(myData)">Change Name</label>
<kid simon="myData"></kid>
<label ng-click="changename(myData)">Change Name</label>
What we are trying to achieve is to somehow relate a particular label to a kid directive, so that when clicking on the label, only the related kid will change its name, rather than all of them.
Hope that makes sense,
As requested in the comments,
please see the plunker :-
plnkr.co/edit/3NMBNTrLT29EIFNo9lbA?p=preview
I am posting a solution here but I am not sure if it solves anything for you.
JS code
var myApp = angular.module('myApp', []);
myApp.controller('notesController', function notesController($scope, $http) {
$scope.myData = [{ name: "Moroni", age: 50, result: "Sodium" },
{ name: "Naomi", age: 50, result: "Sodium" },
{ name: "Rambo", age: 50, result: "Sodium" }
];
$scope.changename = function (h) {
h.name = "Simon";
h.age = "34";
h.result = "This is a test";
};
})
.directive("kid", function () {
return {
restrict: "E",
scope:{
myData:"=simon",
changed:"&change"
},
template: '<input type="text" ng-model="myData.name"/><span>'
+'{{myData.name}}</span><label '
+'ng-click="changed({\'data\':myData});">'
+'Change Name</label><br/>'
};
});
HTML
<div ng-app="myApp" >
<div ng-controller="notesController" >
<kid ng-repeat="data in myData" simon="data" change="changename(data)">
</kid>
</div>
</div>

how do i toggle the visibility of an html element using knockoutjs ?

i am using knockoutjs v3.1.0. i am trying to build a master-detail like view. the problem i am having is that elements are not showing (though they are hiding). my mock code is at http://jsfiddle.net/jwayne2978/qC4RF/3/
this is my html code.
<div data-bind="foreach: users">
<div>Row</div>
<div data-bind="text: username"></div>
<div data-bind="visible: showDetails">
<div data-bind="text: address"></div>
</div>
<div>
<a href="#"
data-bind="click: $root.toggleDetails">
Toggle Div
</a>
</div>
this is my javascript code
var usersData = [
{ username: "test1", address: "123 Main Street" },
{ username: "test2", address: "234 South Street" }
];
var UsersModel = function (users) {
var self = this;
self.users = ko.observableArray(
ko.utils.arrayMap(users, function (user) {
return {
username: user.username,
address: user.address,
showDetails: false
};
}));
self.toggleDetails = function (user) {
user.showDetails = !user.showDetails;
console.log(user);
};
};
ko.applyBindings(new UsersModel(usersData));
what's supposed to happen is that when a user clicks on the link, the corresponding HTML div should show. the console clearly shows that the property is being changed on the user object, but the HTML element's visibility is not changing. i also explicitly made the showDetails property observable, but that did not help.
showDetails : ko.observable(false)
any help is appreciated.
var UsersModel = function (users) {
var self = this;
//var flag=ko.observable(true);
self.users = ko.observableArray(
ko.utils.arrayMap(users, function (user) {
return {
username: user.username,
address: user.address,
showDetails: ko.observable(false) //it should be observable
};
}));
self.toggleDetails = function (user) {
user.showDetails(!user.showDetails());
console.log(user);
};
};
Fiddle Demo

Categories