Reputation: 199
<!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.
Upvotes: 1
Views: 505
Reputation: 1968
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.
Upvotes: 3