Trying to use controllers in AngularJS - angularjs

I have implemented auto-complete feature, now I am trying to integrate into my main application. This is the controller function which I designed.
(function() {
'use strict';
angular
.module('MyApp')
.controller('DemoCtrl', DemoCtrl);
function DemoCtrl($http) {
this.querySearch = function (query) {
return $http.get('http://127.0.0.1:8888/autocomplete/' + escape(query)).then(function(result) {
return result.data;
});
}
}
})();
This is my HTML for the first scenario:
<div class="autocompletedemoFloatingLabel" ng-controller="DemoCtrl as ctrl" ng-app="MyApp" layout="column" ng-cloak="">
<md-content class="md-padding">
<form name="searchForm" ng-submit="$event.preventDefault()">
<div layout-gt-sm="row">
<md-input-container flex="">
</md-input-container>
<md-autocomplete md-floating-label=""
flex=""
md-item-text="item.Symbol"
md-items="item in ctrl.querySearch(ctrl.searchText)"
md-search-text="ctrl.searchText"
md-selected-item="ctrl.selectedItem"
md-no-cache="ctrl.noCache"
md-input-name="autocompleteField"
required="">
<input>
<md-item-template>
<span md-highlight-text="ctrl.searchText">{{item.Symbol+" - "+item.Name+" ("+item.Exchange+")"}}</span>
</md-item-template>
<div ng-messages="searchForm.autocompleteField.$error" ng-if="searchForm.autocompleteField.$touched">
<div ng-message="required">You <b>must</b> have a favorite movie.</div>
<div ng-message="minlength">Your entry is not long enough.</div>
<div ng-message="maxlength">Your entry is too long.</div>
</div>
</md-autocomplete>
</input>
</div>
</form>
</md-content>
</div>
Now the application currently contains controller in this format:
var app = angular.module("assign8", ["ngAnimate"]);
app.controller("MyCtrl", function ($scope) {
$scope.myValue=false;
$scope.myValue_sec = false;
});
I am very new to angular, I am unable to map the first format to the second one. Kindly let me know how can I map first to second. TIA.

I'm not sure where the confusion lies. The two scenarios are very similar.
app.controller("MyCtrl", function ($scope) {
this.querySearch = function (query) { ... }
});

There are two manners to make the binding in AngularJS.
The controller as that is what is done in the first format, you can see DemoCtrl as ctrl in html the ctrl variable represent your controller, in your controller, you see this, every attribut of this can be accessed via ctrl in html. for example: ctrl.myAttribut.
The second manner is the use of $scope service. that is what is done in the second format. every attribut of $scope can be accessed in html as long as the corresponding controller is called. For example: if in your controller you have $scope.myAttribut, in your html you can access like this {{myAttribut}}.

This worked:
<script>
var app = angular.module("MyApp");
app.controller("DemoCtrl", function ($http) {
this.querySearch = function (query)
{
return $http.get('http://127.0.0.1:8888/autocomplete/' + escape(query)).then(function(result) {
return result.data;
});
}
});
</script>

Related

Submit form with angular

I have the following Angular code
controller:
app.controller('MainCtrl', function($scope) {
var vm = this;
vm.job = null;
vm.create = function (job) {
vm.job = job;
}
});
HTML:
<div ng-controller="MainCtrl as vm">
<span data-ng-bind="vm.job.position"></span>
<form name="form" data-ng-submit="vm.create(vm.job)">
<label for="position">Position</label>
<input id="position" name="vm.job.position" type="text" data-ng-model="vm.job.position" />
<button>Create</button>
</form>
</div>
But when I submit the form I don't see the Position value.
Any idea why?
Because
You forgot to add ng-app to the body or html element
You're using angular 1.0.8, which is completely obsolete, and doesn't support controller as.
Note that you don't even need to submit, since the job you're binding is already vm.job. Your create(vm.job) method call does nothing: it assigns vm.job to vm.job.

$scope not getting any values

So this is how my index.html is structured.
<html ng-app='information'>
<body ng-controller="FirstController as first>
<div ng-controller="SecondController as second>
<div id="information">
<myOwnDirective ng-controller="ThirdController as thirdCtrl"></myOwnDirective>
</div>
This is my custom directive.
(function() {
var app = angular.module('information', ['ui.bootstrap']);
app.directive('myOwnDirective', function(){
return {
restrict: 'E',
templateUrl: 'my-own-directive.html',
};
});
This is a custom directive template. my-own-directive.html
<uib-accordion tag ng-repeat="info in first">
<form ng-submit="thirdCtrl.updateInformation()">
<div class="form-group">
<label for="someprop">Property</label> <input type="text" name="someprop"
class="form-control" ng-model="info.propValue"
ng-readonly="info.propValue">
</div>
<button type="submit" class="btn btn-success btn-lg btn-block">Click</button>
</form>
This is my script file: myScript.js
(function() {
angular.module('information').controller('ThirdController', [ '$scope', function($scope) {
console.log("In third controller"); // This prints
this.updateInformation = function() {
console.log("Inside updateInformation");
console.log("Inside scope is: "+ $scope) // It is undefined
};
}]);
})();
What I want to get is get value of info.propValue from the scope but I cant seem to get it. It always shows up as undefined. I have a very long form whose contents I want to read but I cant seem to get the values. Once I have them I will bemaking an Ajax call using $http. Also, if I try to invoke function updateInformation() by doing $scope.updateInformation(), it doesnt invoke, but it does get called if I do this.updateInformation(). Why ?? What am I missing or what am I doing wrong? Any help is appreciated. Have been stuck on it for quite a while. Thank you.

how to add custom md-chips in addition to existing md-chips?

I have designed elements using angular material design . i have used md-chips for rendering skills data as bellow
<md-chips ng-model="user.skills"
readonly="readonly"
placeholder="Enter another skill"
delete-button-label="Remove Skill"
delete-hint="Press delete to remove skill"
secondary-placeholder="Enter a Skill">
<md-chip-template>{{$chip.skill_title}}</md-chip-template>
</md-chips>
In that i have used the user_skills variable to load existing skills.it's loading as i have expected. i need to give the option to add new chips from this . but here when i write skill and enter it'l become empty chip like bellow image.
how to solve it??advanced thanks..
You need to write a function to set 'skill_title'
VIEW
<div ng-controller="BasicDemoCtrl as ctrl" layout="column" ng-cloak="" ng-app="MyApp">
<md-content class="md-padding" layout="column">
<md-chips ng-model="ctrl.skills" readonly="ctrl.readonly" md-transform-chip="ctrl.newSkill($chip)">
<md-chip-template>
<span>
<strong>{{$chip.skill_title}}</strong>
</span>
</md-chip-template>
</md-chips>
</md-content>
</div>
Controller
(function () {
'use strict';
angular
.module('MyApp')
.controller('BasicDemoCtrl', DemoCtrl);
function DemoCtrl ($timeout, $q) {
var self = this;
self.skills = [
{
'skill_title' : 'Angular'
},
{
'skill_title' : 'Material'
},
{
'skill_title' : 'C#'
}
];
self.newSkill = function(chip) {
return {
skill_title: chip
};
};
}
})();
Take a look at this working example.
http://codepen.io/mattspaulding/pen/xZGQyE

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.

Why isn't the Angular ng-click event firing?

I've been following a course to learn angularjs and I can't seem to get a simple ng-click binding to work.
HTML:
<body ng-controller="MainController">
<div ng-app="githubViewer">
<h1>{{message}}</h1>
<div>{{ error }}</div>
{{username}}
<form name="searchUser">
<input type="search" placeholder="Username to find" ng-model="username" />
<input type="submit" value="Search" ng-click="search(username)" />
</form>
<div>
<div>{{user.name}}</div>
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}" title="{{user.name}}">
{{user.gravatar_id}}
</div>
</div>
</body>
Javascript:
(function () {
var module = angular.module("githubViewer", []);
var MainController = function ($scope, $http) {
var onUserComplete = function (response) {
$scope.user = response.data;
};
var onError = function (reason) {
$scope.error = "Could not fetch the user";
$scope.reason = reason;
};
$scope.username = "angular";
$scope.message = "Github Viewer";
$scope.search = function (username) {
$http.get("https://api.github.com/users/" + username)
.then(onUserComplete, onError);
};
};
module.controller("MainController", MainController);
}());
When you click the search button (search for username "odetocode" or "robconery") it is supposed to display an image but the click event does not seem to be firing. I have searched the documentation and looked over the course again but I can't see what I'm doing wrong.
I'm currently using version 1.2.16 of angularjs.
You have the ng-controller declaration outside of the ng-app declaration right now:
<body ng-controller="MainController">
<div ng-app="githubViewer">
It should be the other way around, or have both on the same element
<body ng-app="githubViewer" ng-controller="MainController">
<div>
AngularJS evaluates your code, and checks for any directives you have declared from the ng-app element down, including the element it is declared on; This currently is missing the ng-controller directive, as it is placed on a parent element of the ng-app element.
You need to put the controller within the context of the module to have it within its scope.
Like so
<body ng-app="githubViewer" ng-controller="MainController">
Demo here

Resources