How to display the scope property to text input in angularJS - angularjs

I'm new in AngularJS, and can't do the simple task. I hope that you will help me.
My goal is to display the $scope property "server" from controller to text input in the view when it's loaded:
My controller:
(function () {
'use strict';
angular
.module('app')
.controller('HomeController', homeController);
homeController.$inject = ['authService', 'httpService'];
function homeController(authService, $scope) {
var vm = this;
vm.auth = authService;
$scope.server = SERVER_HOST_NAME;
console.log ($scope.server);
}
})();
var SERVER_HOST_NAME = "anysite.com"; is global.
And I want, that the text input in the view is display that for loading.
My view is
<h4 ng-if="vm.auth.isAuthenticated()">
You are logged in!
</h4>
<h4 ng-if="!vm.auth.isAuthenticated()">
You are not logged in! Please <a ng-click="vm.auth.login()">Log In</a> to continue.
</h4>
<div class="container">
<label>Team city server:</label>
<input ng-model="server" type="text" />
<button ng-click="getBuilds()">Extract</button>
</div>
I use ng-model to bind my property to textinput, but have no idea why it is not working. I guess this is simple task. Thank you.

why you are mixing up both $scope and vm ? use vm and controller as syntax on HTML as follows,
vm.server = SERVER_HOST_NAME;
and the HTML would be,
<input ng-model="vm.server" type="text" />

Related

select option isn't adding object in ionic

I'm trying to add a mongoose object to another mongoose object using a select bar in a form. All the other key,value pairs insert correctly, even the checkbox bool, but the select-option combo won't save the I've done this before with no problem, but in ionic, it doesn't seem to want to work. Is there a work around or am I just messing something up in the code?
$scope.addProperty = function(prop){
console.log(prop);
Props.add(prop)
.then(function(res) {
console.log(res.data);
//window.location.reload();
})
.catch(function(error){
console.log(error);
});
};
<form method = "post" class="form-inline" role="form" action = "localhost:3000/managers/newApt">
<div class="form-group">
<label class="sr-only" >Tenants:</label>
<select ng-model="prop.tenants" class="column medium-3" ng-options="manager.name for manager in allManagers"> </select>
</div>
<div class="form-group">
<label class="sr-only">Address</label>
<input type="text" class="form-control" ng-model='prop.address'>
</div>
<button type="submit" class="btn btn-default" ng-click='addProperty(prop)'>Add Property</button>
</form>
try to use this video tutorial they use var controllerName = this, inside controller and reference methods and properties of the controller through var controllerName, for example this is a controller:
angular
.module('your-app-module')
.controller('ExampleController', function ($scope, $state) {
//This var is to bind methods and vars in view(html) to this specific controller
var ExmpleCtrl = this; //this is the var that is going to replace $scope
//NOTICE no $scope but rather ExmpleCtrl
ExmpleCtrl.goToState = function (state) {
$state.go(state);
};
});
Now in your html try:
<ion-view ng-controller="ExampleController as exmpleCtrl">
<ion-content>
<!-- notice how I use exmpleCtrl instead of $scope to access controller or to pass info -->
<div ng-click="exmpleCtrl.doSomething()">
</ion-view>
If you still have doubt check this short video (ignore it's for webstorm the way they bind the controller to the a variable inside controller referenced to this is what is useful): http://blog.jetbrains.com/webstorm/2014/03/angularjs-workflow-in-webstorm/

AngularJs service not injected in controller

I am having trouble with something very simple like inject a basic service into a controller and despite reading documentation and other SO question i really don't see the mistake i'm making.
Here's my simplified code:
angular.module ('travelApp', ['ui.bootstrap', 'ngRoute'])
//CONTROLLERS
.controller('searchController', ['$scope','myParams', function ($scope,ngRoute,myParams){
$scope.place = myParams.place;
$scope.$watch('place', function(){
myParams.place = $scope.place;
});
$scope.bind = function(){
console.log(myParams.getPlace);
};
}])
//SERVICES
.service('myParams', function(){
this.place = 'start';
});
//MY HTML
<div class="container" ng-app="travelApp">
<div class="jumbotron" id="searchPage" ng-controller="place">
<div>
<h3>Start Here</h3>
<input type="text" class="form-control" id="searchBar" ng-model="place">
<a type="button" class="btn btn-default" ng-click="bind()">bind data</a>
</div>
</div>
I have tried a number of things in the past few hours but keep getting the
"TypeError: Cannot set property 'place' of undefined"
It seems the service is just no available inside the controller, i don't know if it has something to do with routing but i doubt so.
Can someone please point me in the right direction?
Here is a Plunker
Your dependencies must match if you use array syntax. Remove ngRoute from the controller's arguments.
.controller('searchController', ['$scope','myParams', function ($scope, myParams){

Not able to access ng-model variables when using ng-view

I have the following Form which I am including in the main app through ng-view
Form Snippet
<form action = "#" method="post" class="form-horizontal" id="commentForm" role="form">
<div class="form-group">
<div class="col-sm-10">
<textarea class="form-control" type="text" ng-model="userComment" placeholder="New Discussion Topic" rows="5"></textarea>
</div>
</div>
<div class="form-group" id="div_submitComment">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn" type="button" id="submitComment" ng-click="vm.addComment()">Submit comment</button>
</div>
</div>
</form>
Upon clicking the submit button, the controller function will be called. In the controller function, I am not able to access the variable $scope.userComment
Controller Snippet
(function () {
'use strict';
angular
.module('app')
.controller('DiscussionBoardController', DiscussionBoardController);
DiscussionBoardController.$inject = ['UserService', '$rootScope', '$scope', '$cookieStore', 'AuthenticationService'];
function DiscussionBoardController(UserService, $rootScope, $scope, $cookieStore, AuthenticationService) {
function addComment() {
$.getJSON(
"http://localhost/DBoardPage/server/discussion-board/postComment.php", // The server URL
{ userName: $scope.currentUser , userComment:$scope.userComment , commentID:0 }, // Data you want to pass to the server.
$scope.addCommentResponse // The function to call on completion.
);
};
/*End - Discussion Board related Functions*/
}
})();
Though I know that a child scope will be created when we use ng-include, ng-view and ng-repeat, I am not getting an example to explain the usage.
Please let me know how I can get around this preoblem
Are you sure it isn't $scope.currentUser that doesn't exist? You are using a variable that isn't declared.
Try adding:
$scope.currentUser = "";
$scope.userComment = "";
Since you are using AngularJS it might be a better idea creating your function the Angular way.
$scope.addComment = function(){....
If it still doesn't work show more of your setup.

Accessing scope in ngRoute

I have a simple 1-page app design with two inputs in a static sidebar and an ng-view in which I load JSON data via a $http request in the controller. I'm using ngRoute to load different templates into the view.
This is sample code for my controller:
someModule.controller('JobPostingsCtrl', function($scope, $http) {
$scope.cityFilter = function() {
$http.get("dir/"+$scope.locationFilter+".json")
.then(function(res){
$scope.jobs = res.data;
});
};
$scope.searchFilter = function (jobposting) {
var keyword = new RegExp($scope.keyword, 'i');
return !$scope.keyword || keyword.test(jobposting.title);
};
$scope.locationFilter = $scope.locationFilter || 'all';
$http.get("dir/"+$scope.locationFilter+".json")
.then(function(res){
$scope.jobs = res.data;
});
});
In my index.html I mark up the sidebar with the input fields that are models for locationFilter and keyword:
<input type="search" name="search" id="search" ng-model="keyword">
<input type="search" name="location" id="location" ng-model="locationFilter">
<button id="go" ng-click="cityFilter();">Click</button>
On load, the view displays the 'all' data normally and the searchFilter (based on the keyword model) works on the scope as intended.
However, when I click the cityFilter() button, the controller does get new data (if I do console.log($scope.jobs) inside my cityFilter() function, I see the intended JSON object in my console) but the view does not reflect these changes.
Why does the view reflect the changes in the keyword model, but not the cityFilter() changes? If the scope is different, as I first thought, shouldn't both be ineffective?
I set it up this way because I want the sidebar to be accessible from anywhere in the application. I am mostly confused by the fact that my controller seems to be aware of the changes to $scope variables but doesn't 'transmit' them to the view, even though ng-click is inside an $apply according to Angular documentation. Any idea of what I'm doing wrong?
EDIT: The way my initial template is loaded using routeProvider:
angular.module('someModule', ['ngRoute']).config(['$routeProvider', '$locationProvider',
function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'dir/views/job-posting.html',
controller: 'JobPostingsCtrl'
})
...
The HTML for the template:
<div ng-repeat="job in jobs | filter:searchFilter>
{{ job.someProperty }}
</div>
The index.html:
<div ng-controller="MasterCtrl">
<div id="sidebar" ng-controller="JobPostingsCtrl">
<input type="search" name="search" id="search" ng-model="keyword">
<input type="search" name="location" id="location" ng-model="locationFilter">
<button id="go" ng-click="cityFilter();">Click</button>
</div>
<div ng-view></div>
</div>

AngularJS data binding in controller

This works great:
<input type="text" class="search" data-ng-model="name"/>
<div class="rf-contact" data-ng-repeat="contact in contacts | filter: name">
<p class="rf-first">{{contact.first_name}} {{contact.last_name}}</p>
</div>
However I need to implement filter in the controller:
var contactsController = function ($scope, $filter){
$scope.contacts = contacts;
$scope.filteredContacts = $filter('filter')($scope.contacts, $scope.name);
}
<input type="text" class="search" data-ng-model="name"/>
<div class="rf-contact" data-ng-repeat="contact in filteredContacts">
<p class="rf-first">{{contact.first_name}} {{contact.last_name}}</p>
</div>
The problem with the code above is that the data binding is lost. When the data is changing in the text field, the filtering is not happening. Do I need to explicitly set event listeners for the input field in my controller? thanks.
You could try $watch-ing the name:
var contactsController = function ($scope, $filter){
$scope.contacts = contacts;
$scope.filteredContacts = $filter('filter')($scope.contacts, $scope.name);
$scope.$watch('name', function(newValue, oldValue) {
$scope.filteredContacts = $filter('filter')($scope.contacts, newValue);
});
}
For more info on $watch: http://docs.angularjs.org/api/ng/type/$rootScope.Scope. Anytime "something" happens through Angular (like the value of "name" changes because you type something in the text field), Angular will fire the watch you created and execute the function. This is necessary here because the initial code you wrote builds the filteredContacts scope variable when the controller is instantiated and there's nothing re-evaluating this expression.
While this solution with an explicit $watch will work, it's a little hacky. This kind of logic is better encapsulated in a custom filter. You can easily build one with arbitraty logic as described in http://docs.angularjs.org/tutorial/step_09.
Try the following
var contactsController = function ($scope, $filter){
$scope.filterContacts = function(){
$scope.contacts = contacts;
$scope.filteredContacts = $filter('filter')($scope.contacts, $scope.name);
}
}
<input type="text" class="search" data-ng-model="name" ng-change="filterContacts()"/>
<div class="rf-contact" data-ng-repeat="contact in filteredContacts">
<p class="rf-first">{{contact.first_name}} {{contact.last_name}}</p>
</div>
Here's a jsfiddle of this in action:
http://jsfiddle.net/CAuq9/

Resources