AngularJS submit function not working - javascript

I'm getting my first taste of AngularJS, having build quite a lot with laravel as a backend. So I installed laravel and created an index.blade.php file. In it I have a ng-submit, but I can't get it to work.
<!doctype html>
<html lang="en" ng-app>
<head>
<meta charset="UTF-8">
<title>Laravel and AngularJS test</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<script src="/js/main.js"></script>
</head>
<body>
<div ng-controller="TodoController">
<h1>Todo</h1>
<input type="text" placeholder="Search todos" ng-model="search">
<ul>
<li ng-repeat="to in todos | filter:search">
#{{ todo.body }}
</li>
</ul>
<form ng-submit="addTodo()">
<input type="text" placeholder="Add a todo" ng-model="newTodo">
<button type="submit">Add todo</button>
</form>
</div>
</body>
</html>
main.js
function TodoController($scope) {
$scope.todos = [
{ body: 'Groceries' },
{ body: 'Drive' }
];
$scope.addTodo = function() {
$window.alert('test');
};
}

Have a fiddle
angular.module('todoApp', [])
.controller('TodoController', ['$scope', '$window', function ($scope, $window) {
$scope.todos = [
{ body: 'Groceries' },
{ body: 'Drive' }
];
$scope.addTodo = function() {
$window.alert('test');
};
}]);
With html like:
<div ng-app="todoApp">
<div ng-controller="TodoController">
<h1>Todo</h1>
<input type="text" placeholder="Search todos" ng-model="search">
<ul>
<li ng-repeat="to in todos | filter:search">
#{{ to.body }}
</li>
</ul>
<form ng-submit="addTodo()">
<input type="text" placeholder="Add a todo" ng-model="newTodo"/>
<button type="submit">Add todo</button>
</form>
</div>
</div>

function TodoController($scope,$window) { .....
try to modify with this way :)

Controller should be define like following in main.js
angular.module('todoApp', []) .controller('TodoController', ['$scope', function($scope) {
}]);
Give name to ng-app to ng-app='todoApp' in html tag

Related

angularjs controller not updating page content

I'm doing an simple app-ToDoList with login page.the second page have a controller that update dynamically the content of my ToDoList, unfortunately when I launch my application the controller not update the page...there someone that could advice me what's wrong? maybe I'm missing something..
here the application with the code :
http://plnkr.co/edit/IIYlc1RbEeW8mn9L6YVL?p=preview
This is the page where load the contents.
<html ng-app="toDoApp" ng-controller="toDoController">
<head>
<title>Tasks App</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-route.min.js"></script>
<script src="app.js" type="text/javascript"></script>
<script src="ToDocontroller.js" type="text/javascript"></script>
</head>
<body>
<h1>My To-do List</h1>
<h2>Tasks</h2>
<table>
<tr><td>
<h3>Active ({{ tasks.length }})</h3>
<span ng-hide="tasks.length">You have no active tasks!</span>
<div ng-repeat="task in tasks">
<input type="checkbox" ng-click="transferTo($index, tasks, completed)" /> {{ task }}<br />
</div>
</td><td>
<div ng-show="completed.length">
<h3>Completed ({{ completed.length }})</h3>
<div ng-repeat="task in completed">
<input type="checkbox" ng-click="transferTo($index, completed, tasks)" checked /> <span class="complete">{{ task }}</span><br />
</div>
</div>
</td></tr>
</table>
<h2>Add a Task</h2>
<form ng-submit="addTask()">
<input type="text" placeholder="Description" ng-model="newTaskName" />
<input type="submit" value="Add" />
</form>
</body>
</html>
Here my controller
angular.module('toDoApp', [])
.controller('toDoController', ['$scope', function($scope) { alert('1');
$scope.tasks = ['Do the laundry'];
$scope.completed = [];alert('1');
$scope.newTaskName = '';
alert('2');
$scope.addTask = function() {
var name = $scope.newTaskName;
if (name && $scope.tasks.indexOf(name) == -1
&& $scope.completed.indexOf(name)) {
$scope.tasks.push(name);
$scope.newTaskName = '';
}
};
$scope.transferTo = function(index, start, end) {
end.push(start[index]);
start.splice(index, 1);
}
}]);
tnx in advance
So many mistakes. This is just sample. You should use $route (ng-view or ui-view) for route navigation.. I was updated plnkr.
http://embed.plnkr.co/C1ubxufRQHN4rfGooxeF/

Controller data not passed to directive

I started looking into angular and cannot seem to figure out why my data is not passed to my directive. I have code here: https://plnkr.co/edit/ONwYevQ4NbvBVjTwARHl?p=preview
My Code:
app.js:
var app = angular.module('mjApp', []);
app.controller('MainController', ['$scope', '$http', function ($scope, $http) {
$scope.name = "m.jacionis";
$scope.avatar = null;
$scope.fetchData = function(){
var callUrl = 'https://api.github.com/search/users?q=' + $scope.name;
$scope.avatar = "http://images.clipartpanda.com/sad-face-clipart-black-and-white-9c4eqRyyi.png";
$http({
method: 'GET',
url: callUrl
}).then(function successCallback(response) {
$scope.avatar = response.data.items.length > 0 ?
response.data.items[0].avatar_url : $scope.avatar;
console.log($scope.avatar);
}, function errorCallback(response) {
console.log('avatar stays the same');
});
};
}]);
app.directive("mjDirective", function(){
return {
restrict: "EA",
templateUrl: 'template.html',
scope: {
name: "=name",
avatar: "=avatar"
}
};
});
index.html:
<!DOCTYPE html>
<html ng-app="mjApp">
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="parent" ng-controller="MainController">
<div class="line">
<input type='text' ng-model='name' />
<input type="button" ng-click="fetchData()" value="Submit User Name" />
</div>
<mj-directive name=name userAvatar=userAvatar></mj-directive>
</div>
</body>
</html>
template.html:
<div class='line'>
<p>Name : <strong>{{name}}</strong></p>
<img class="avatar" src={{avatar}}/>
</div>
name value is passed, but avatar value which I get when I fetch data isn't. I cannot seem to figure out, why it is like that. Any ideas or suggestions would help a lot.
I think you have taken wrong name userAvatar instead of avatar since you binded avatar
your bindings,
scope: {
name: "=name",
avatar: "=avatar"
}
So, you have to take name and avatar in directive.
<body>
<div class="parent" ng-controller="MainController">
<div class="line">
<input type='text' ng-model='name' />
<input type="button" ng-click="fetchData()" value="Submit User Name" />
</div>
<mj-directive name=name avatar=avatar></mj-directive>
</div>
</body>
change directive,
<mj-directive name=name avatar=avatar></mj-directive>
I think you need to wrap the name and avatar in strings when you use them in HTML.
<mj-directive name="name" userAvatar="userAvatar"></mj-directive>
Also inside the directive you should have:
scope: {
user: "=name"
avatar: "=userAvatar"
}

ng-click the button with no response

The button is not work.
I click the button ng-click="goSearchTitle()" and it has no response.
Why it doesn't work?
<body ng-app="myapp">
<div ng-contoller="searchbyTitle">
<h3>Search by Title</h3>
<div>
<input type="text" id="searchTitle" placeholder="Enter a title" ng-model="searchTitle"/>
<button type="button" id="goSearchTitle" ng-click="goSearchTitle()">Search</button>
</div>
</div>
<script>
angular.module("myapp", []).controller("searchbyTitle", function($scope, $http) {
$scope.goSearchTitle = function(){
alert($scope.searchTitle);
}
});
</script>
</body>
Your app name is wrong.
<body ng-app="myapp">
Otherwise, angular will give an injector module error. You should always open console and see the errors to understand better
You have typo # ng-contoller, it is ng-controller
var myApp = angular.module("myapp", []);
myApp.controller("searchbyTitle", function($scope, $http) {
$scope.goSearchTitle = function() {
alert($scope.searchTitle);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myapp">
<div ng-controller="searchbyTitle">
<h3>Search by Title</h3>
<div>
<input type="text" id="searchTitle" placeholder="Enter a title" ng-model="searchTitle" />
<button type="button" id="goSearchTitle" ng-click="goSearchTitle()">Search</button>
</div>
</div>
</body>

Angular- View Not loading

I wrote a file new.html and I am trying to test navigation. But when i load the page View1.html should be loaded but it shows a blank page.
Here is my new.html:
<!DOCTYPE html>
<html data-ng-app="demoApp">
<head>
<title> Angular Test</title>
</head>
<body>
<div>
<div data-ng-view></div>
</div>
<script src = "Scripts/angular.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>
</body>
<script>
var demoApp = angular.module('demoApp', ['ngRoute']);
demoApp.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'SimpleCtr',
templateUrl: 'View1.html'
})
.when('/2',
{
controller: 'SimpleCtr',
templateUrl: 'View2.html'
})
.otherwise({ redirectTo: '/' });
});
demoApp.controller('SimpleCtr', function($scope) {
$scope.customers = [
{ name:'Rajat', city:'Kanpur' },
{ name:'Adarsh', city:'Lucknow' },
{ name:'Manoj', city:'Banaras' }
];
$scope.addCustomer = function() {
$scope.customers.push({ name: $scope.newCustomer.name, city: $scope.newCustomer.city });
}
});
</script>
</html>
And here is my View1.html:
<div class="container">
<h2> View 1 </h2>
Name: <br/>
<input type="text" data-ng-model="filter.name"/>
<br/>
<ul>
<li data-ng-repeat = "cust in customers | filter:filter.name | orderBy:'city'"> {{cust.name}} </li>
</ul>
Customer Name: <br/>
<input type="text" data-ng-model="newCustomer.name"/>
<br />
Customer City: <br />
<input type="text" data-ng-model="newCustomer.city"/>
<br />
<button data-ng-click = "addCustomer()"> Add Customer </button>
<a href = "#/2" > View 2 </a>
</div>
Here is View2.html:
<div class="container">
<h2> View 2 </h2>
City:
<br/>
<input type="text" data-ng-model="city" />
<br/>
<ul>
<li data-ng-repeat = "cust in customers | filter:filter.city | orderBy:'city'"> {{cust.name}} </li>
</ul>
</div>
Please help me where i am going wrong?
You are missing a closing bracket in your code on line 8
<!DOCTYPE html>
<html data-ng-app="demoApp">
<head>
<title> Angular Test</title>
</head>
<body>
<div>
<div data-ng-view> </div> <!-- right here -->
</div>
I created a plunker here: http://plnkr.co/edit/uj4S1ybv7vJSsQctG1nD
http://plnkr.co/edit/uj4S1ybv7vJSsQctG1nD
Your views aren't loaded because you try to access them using the file:// protocol. If you put your website on a HTTP server (XAMPP for example) you'll get the desired result.
It works fine with Plnkr. http://plnkr.co/edit/NmfnOMTRHXzsLkcHfgZX?p=preview
My best guess is you are not running the file in HTTP server. The simplest HTTP server is, run this command in your working directory:
python -m SimpleHTTPServer
Then, request your program in browser
localhost:8000/new.html

Angularjs ng-repeat, ng-form and validation error

A simplified version of the code:
<!DOCTYPE html>
<html ng-app="main">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://code.angularjs.org/1.4.3/angular.min.js"></script>
<script>
var app = angular.module("main", []);
app.controller("TestController", function($scope) {
$scope.addresses = [{street: ""}, {street: ""}];
$scope.next = function() {
if ($scope.addressMainForm.addressForm.$valid) {
console.log("valid");
} else {
console.log("invalid");
}
$scope.addresses.push({street: ""});
};
$scope.remove = function(index) {
$scope.addresses.splice(index, 1);
};
});
</script>
</head>
<body>
<div ng-controller="TestController" style="width: 500px;">
<form name="addressMainForm">
<div ng-repeat="address in addresses">
<ng-form name="addressForm">
<input ng-model="address.street" required name="street" type="text" placeholder="street" />
<button ng-if="$index > 0" ng-click="remove($index)">REMOVE</button>
</ng-form>
<br>
</div>
</form>
<br>
<button ng-click="next()">NEXT</button>
</div>
</body>
</html>
which looks in the browser like this:
When I click "REMOVE" and then "NEXT" - javascript error is produced:
Error: $scope.addressMainForm.addressForm is undefined
Why is it undefined if there is clearly still one element remaining in the array? Everything otherwise works fine (console.log output), until all the elements are removed but the last one and "NEXT" is clicked.
When you call $scope.addressMainForm.addressForm.$valid , you are attempting to call check to see if the adressForm element is valid, but your remove function has removed the addresses entry associated with that element. So the form indeed still exists, but that call becomes illegal.
Try this:
<!DOCTYPE html>
<html ng-app="main">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://code.angularjs.org/1.4.3/angular.min.js"></script>
<script>
var app = angular.module("main", []);
app.controller("TestController", function($scope) {
$scope.addresses = [{street: ""}, {street: ""}];
$scope.next = function() {
if ($scope.addressMainForm.$valid) {
console.log("valid");
} else {
console.log("invalid");
}
$scope.addresses.push({street: ""});
};
$scope.remove = function(index) {
$scope.addresses.splice(index, 1);
};
});
</script>
</head>
<body>
<div ng-controller="TestController" style="width: 500px;">
<form name="addressMainForm">
<div ng-repeat="address in addresses">
<ng-form name="addressForm">
<input ng-model="address.street" required name="street" type="text" placeholder="street" />
<button ng-if="$index > 0" ng-click="remove($index)">REMOVE</button>
</ng-form>
<br>
</div>
</form>
<br>
<button ng-click="next()">NEXT</button>
</div>
</body>
</html>

Categories

Resources