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

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

Related

Data binding in angularjs after http call

I'm new to AngularJS and I'm trying to bind some data I fetch with an Http call when user clicks a button. Data binding works fine when I use it outside of test() but it does not inside test() which gets called on a button click.
What am I doing wrong?
<head>
<script>
function test() {
fetch(url)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
var response = myJson;
var results = parseJSON(response);
angular.module("blabla", [])
.controller("myController", function($scope) {
$scope.test= {};
$scope.test.title = "testttt!";
});
});
}
</script>
</head>
<body ng-app="blabla">
<div class="search">
<form id="search_form" method="get" onSubmit="return test()">
<input type="text" class="_search" placeholder="Search" id="search_">
<input title="Search" value="" type="submit" class="search_btn">
</form>
</div>
<div ng-controller="myController">
<h2>Welcome {{test.title}}</h2>
</div>
</body>
Replace onSubmit="return test()" by onSubmit="test()"
The Angular interpreter is trying to invoke the statement (I believe that it thinks it is a function) return (with parameters test()
Also, test() needs to be declared in the $scope of your controller myController.
It might be a good idea to get a skeleton demo Angular app and try to understand how it works by making small modifications.

Adding ng-model directive to dynamically created input tag using AngularJs

I am trying that on a button click, a div and and input tag are created and the input tag contain ng-model and the div has binding with that input.
Kindly suggest some solution.
You can create the div and input beforehand and and do not show it by using ng-if="myVar". On click make the ng-if="true".
<button ng-click="myVar = true">
In controller : $scope.myVar = false;
$scope.addInputBox = function(){
//#myForm id of your form or container boxenter code here
$('#myForm').append('<div><input type="text" name="myfieldname" value="myvalue" ng-model="model-name" /></div>');
}
Here is another solution, in which there's no need to create a div and an input explicitly. Loop through an array of elements with ng-repeat. The advantage is that you will have all the values of the inputs in that array.
angular.module('app', [])
.controller('AppController', AppController);
AppController.$inject = ['$scope'];
function AppController($scope) {
$scope.values = [];
$scope.add = function() {
$scope.values.push('');
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="AppController">
<button ng-click="add()">Click</button>
<div ng-repeat="value in values track by $index">
<input type="text" ng-model="values[$index]"/>
<div>{{values[$index]}}</div>
</div>
<pre>{{values}}</pre>
</div>
UPDATE. And if you want only one input, it's even simpler, using ng-show.
angular.module('app', []);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<button ng-click="show = true">Click</button>
<div ng-show="show">
<input type="text" ng-model="value"/>
<div>{{value}}</div>
</div>
</div>
You should use $compile service to link scope and your template together:
angular.module('myApp', [])
.controller('MyCtrl', ['$scope', '$compile', '$document' , function MyCtrl($scope, $compile, $document) {
var ctrl = this;
var inputTemplate = '<div><span ng-bind="$ctrl.testModel"></span>--<span>{{$ctrl.testModel}}</span><input type="text" name="testModel"/></div>';
ctrl.addControllDynamically = addControllDynamically;
var id = 0;
function addControllDynamically() {
var name = "testModel_" + id;
var cloned = angular.element(inputTemplate.replace(/testModel/g, name)).clone();
cloned.find('input').attr("ng-model", "$ctrl." + name); //add ng-model attribute
$document.find('[ng-app]').append($compile(cloned)($scope)); //compile and append
id++;
}
return ctrl;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.6.2/angular.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl as $ctrl">
<input type="button" value="Add control dynamically" ng-click="$ctrl.addControllDynamically()"/>
</div>
</div>
UPDATE: to add a new compiled template each time the button is clicked, we need to make a clone of the element.
UPDATE 2: The example above represents a dirty-way of manipulating the DOM from controller, which should be avoided. A better (angular-)way to solve the problem - is to create a directive with custom template and use it together with ng-repeat like this:
angular.module('myApp', [])
.controller('MyCtrl', ['$scope', function MyCtrl($scope) {
var ctrl = this;
ctrl.controls = [];
ctrl.addControllDynamically = addControllDynamically;
ctrl.removeControl = removeControl;
function addControllDynamically() {
//adding control to controls array
ctrl.controls.push({ type: 'text' });
}
function removeControl(i) {
//removing controls from array
ctrl.controls.splice(i, 1);
}
return ctrl;
}])
.directive('controlTemplate', [function () {
var controlTemplate = {
restrict: 'E',
scope: {
type: '<',
ngModel: '='
},
template: "<div>" +
"<div><span ng-bind='ngModel'></span><input type='type' ng-model='ngModel'/></div>" +
"</div>"
}
return controlTemplate;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.6.2/angular.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl as $ctrl">
<input type="button" value="Add control dynamically" ng-click="$ctrl.addControllDynamically()"/>
<div ng-repeat="control in $ctrl.controls">
<control-template type="control.type" ng-model="control.value"></control-template>
</div>
</div>
</div>

Dynamic controller change in angularjs

I need to dynamically change controller of one particular div by clicking some input buttons.
Why it works the first way, but doesn't work the second way if I replace one-element array by controller itself (see code below).
And how to implement such functionality in a better way?
Plnkr with one-element array (works)
index.html
<body ng-app="myApp">
<div ng-controller="MyCtrl">
Hello, {{name}}!
<input type="button" value="click me" ng-click="changeCtrl(0)"/>
<input type="button" value="click me" ng-click="changeCtrl(1)"/>
<input type="button" value="click me" ng-click="changeCtrl(2)"/>
<div ng-repeat = "ctrl in curCtrl" ng-controller="ctrl">
{{ blah }}
</div>
</div>
</body>
</html>
script.js
var myApp = angular.module('myApp', []);
myApp.controller("MyCtrl", MyCtrl);
function MyCtrl($scope) {
$scope.name = 'Username';
$scope.ctrls = [ctrlA, ctrlB, ctrlC];
$scope.curCtrl = [ctrlA];
$scope.changeCtrl = function (idx) {
$scope.curCtrl = [$scope.ctrls[idx]];
}
}
function ctrlA($scope) {$scope.blah = "One";}
function ctrlB($scope) {$scope.blah = "Two";}
function ctrlC($scope) {$scope.blah = "Three";}
Plnkr with controller instead (doesn't work)
index.html
<body ng-app="myApp">
<div ng-controller="MyCtrl">
Hello, {{name}}!
<input type="button" value="click me" ng-click="changeCtrl(0)"/>
<input type="button" value="click me" ng-click="changeCtrl(1)"/>
<input type="button" value="click me" ng-click="changeCtrl(2)"/>
<div ng-controller="curCtrl">
{{ blah }}
</div>
</div>
</body>
</html>
script.js
var myApp = angular.module('myApp', []);
myApp.controller("MyCtrl", MyCtrl);
function MyCtrl($scope) {
$scope.name = 'Username';
$scope.ctrls = [ctrlA, ctrlB, ctrlC];
$scope.curCtrl = ctrlA;
$scope.changeCtrl = function(idx) {
$scope.curCtrl = $scope.ctrls[idx];
}
}
function ctrlA($scope) {$scope.blah = "One";}
function ctrlB($scope) {$scope.blah = "Two";}
function ctrlC($scope) {$scope.blah = "Three";}
It works with ng-repeat because ng-repeat destroys and re-compiles the HTML when the array reference changes. You would have to compile manually if you want the same result without an array, using the $compile service on the $element. It could be done in your controller, but a directive might be better.
You may also want to take advantage of client-side routing to accomplish this (ui-router allows nested states).
Check out these answers:
Dynamic NG-Controller Name
Dynamically assign ng-controller on runtime
Otherwise, you could use a quick hack with ng-if and $timeout:
$scope.changeCtrl = function(idx) {
// ng-if sees null and destroys the HTML
$scope.curCtrl = null;
$timeout(function() {
// ng-if sees a new object and re-compiles the HTML
$scope.curCtrl = $scope.ctrls[idx];
});
}
<div ng-if="curCtrl" ng-controller="curCtrl">
{{ blah }}
</div>

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.

Resources