I want to add a $watch to watch $scope.data is changed or not, but it cant't work
[http://jsbin.com/biqesojaqu/1/edit?html,js,console,output][1]
app.html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-app="App" ng-controller="TestController">
<div>
<ul>
<li ng-repeat="item in data"> {{ item.name }}--{{ item.status }}</li>
<button ng-click="addOnePerson()">ADD</button>
</ul>
</div>
</body>
</html>
app.js
var App = angular.module("App", []);
App.controller('TestController', function ($scope) {
$scope.data = [
{name: 'cc', status: true},
{name: 'bob', status: false}
];
$scope.name = 'nataila';
$scope.addOnePerson = function () {
var personCount = $scope.data.length;
personCount += 1;
$scope.data.unshift({name: 'cc'+personCount, status: true});
};
$scope.$watch('data', function (){
console.log('has changed');
});
});
when I click the button, I think console will output has chenged, but it's nothing
please tell me Why, and it's Good to help me in JSbin
Use $watchCollection for an array or object
$scope.$watchCollection('data', function (){
console.log('has changed');
});
JSBin
Related
I am new in angularjs and trying to getting selected value in controller. It is working properly at front-end but the selected value getting undefined in controller, How can i access to selected value in controller?
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-change="changed()" ng-model="selectedOption" class="form-control">
<option ng-repeat="x in options" value="{{x.reason}}">{{x.reason}}</option>
</select>
{{selectedOption}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.options = [{reason: "Facebook"},
{reason: "Instagram"},
{reason: "Google"},
{reason: "Twitter"},
{reason: "SMS"}];
$scope.changed = function () {
console.log("selected Options: " + $scope.selectedOption);
}
});
</script>
</body>
</html>
Your code works.
DEMO
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.options = [
{reason : "Facebook"},
{reason : "Instagram"},
{reason : "Google"},
{reason : "Twitter"},
{reason : "SMS"},
];
$scope.changed= function() {
console.log("selected Options: "+$scope.selectedOption);
}
});
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-change="changed()" ng-model="selectedOption" class="form-control">
<option ng-repeat="x in options" value="{{x.reason}}">{{x.reason}}</option>
</select>{{selectedOption}}
</div>
Seems everything is okay, just call $scope.selectedOption from anywhere in controller.
Its working perfectly! I tried this in JSFiddle and its working as it should!
Even this is working too.
$scope.changed= function() {
console.log("selected Options: "+$scope.selectedOption);
}
Look here: https://jsfiddle.net/vLam3pe0/
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.selectedOption;
$scope.options = [{reason: "Facebook"},
{reason: "Instagram"},
{reason: "Google"},
{reason: "Twitter"},
{reason: "SMS"}];
$scope.changed = function () {
console.log("selected Options: " + $scope.selectedOption);
}
});
</script>
Okay so I am trying to learn how to create a modular angular app, but I don't really know how it would look. Based on my code what would I need to do to make it modular? My app is pretty small but I still want to try and get the idea down as for how to create a modular app so that I can just do that from the beginning the next time I create a web app. I didn't include the css as it seems irrelevant for this question. Help would be greatly apprciated.
index.html
<!DOCTYPE html>
<html>
<head>
<header>To do App</header>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>To do App</title>
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"> </script>
<script type='text/javascript' src="//use.edgefonts.net/vast-shadow:n4:all.js"></script>
<script type='text/javascript' src="//use.edgefonts.net/vast-shadow:n4:all;megrim.js"></script>
<script type='text/javascript' src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script type='text/javascript' src="js/index.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div ng-app="demoApp">
<script type="text/ng-template" id="partials/edit-form.html">
<div ng-show="todo.editMode">
<input ng-model="todo.text" />
<button ng-click="save(todo)">save</button>
</div>
</script>
<div class="todo-wrapper" ng-controller="todoCtrl">
<h2>You have <span class="emphasis">{{getTotalTodos()}}</span> tasks</h2>
<input class="search-input" type="text" ng-model="searchText" placeholder="enter search term" />
<ul>
<li ng-repeat="todo in todos | filter: searchText">
<span>{{todo.text}}: {{todo.date_created}}</span>
<div ng-include="'partials/edit-form.html'"></div>
<button class="clear-btn" ng-click="removeTask(todo)">Remove</button>
<button class="clear-btn" ng-click="editTask(todo)">Edit</button>
</li>
</ul>
<form>
<input class="add-input" placeholder="task name" type="text" ng-model="text" ng-model-instant />
<button class="add-btn" ng-click="addTask()"><h2>Add</h2></button>
</form>
</div>
</body>
</html>
index.js
angular.module('demoApp', [])
.controller('todoCtrl', TodoCtrl);
function TodoCtrl($scope) {
$scope.todos = [{
id: 1,
text: 'Mow the lawn',
selected: false
}, {
id: 2,
text: 'Wash the car',
selected: false
}];
$scope.id = $scope.todos.length + 1; //later create an uuid
$scope.getTotalTodos = function () {
return $scope.todos.length;
};
$scope.addTask = function () {
$scope.todos.push({
editMode: false,
text: $scope.text,
id: $scope.id,
date_created: Date.now,
selected: false
});
$scope.text = '';
$scope.id = '';
};
$scope.removeTask = function (todo) {
/*$scope.todos = _.filter($scope.todos, function (todo) {
return !todo.selected;
});*/
$scope.todos.pop(todo);
//update server now with ngResource...
};
$scope.showDetails = function (task_id) {
var found = $filter('filter')($scope.todos, {
id: task_id
}, true);
if (found.length) {
$scope.selected = JSON.stringify(found[0]);
} else {
$scope.selected = 'Not found';
}
}
$scope.editTask = function(todo) {
todo.editMode = true;
console.log(todo);
};
$scope.save = function(todo) {
todo.editMode = false;
// update data at server now too. $scope.todos is up-to-date
}
$scope.updateTask = function (task_id) {
// search $scope.todos for the item to update
var indexOfTask;
for (var i = 0; i < $scope.todos.length; i++) {
if ($scope.todos[i].id === $scope.id) indexOfTask = i;
$scope.todos[i] = todo;
$scope.todos.push();
$scope.text = '';
$scope.id = '';
}
// update the todo
};
}
Essentially just make a new file for every angular whatever (factory, controller, directive, etc.)
I use this syntax
angular.module('myapp.functionName.type', [])
.type('functionName',);
Then in your app.js, in your case index.js
angular.module('myapp', ['myapp.functionName.type', ... ]) ;
I've just started learning Angular JS but soon I got a problem which I don't know how to resolve.
This code prints:
<h1>{{author[0].name}}</h1>
<p>{{author[0].title+ ', '+author[0].company}}
instead of:
<h1>MKJ</h1>
<p>Web Developer, Student Organization</p>
The code is given here as well:
<!doctype html>
<!-- Declaring the ng-app -->
<html ng-app="myApp">
<head>
<title>Parking</title>
<!-- Importing the angular.js script -->
<script src="lib/angular/angular.min.js"></script>
<script>
var myApp = angular.module("myApp", []);
myApp.controller("MyController", function ($scope){
$scope.author = {
'author': 'MKJ',
'title': 'Web Developer',
'company': 'Student Organization',
};
}
</script>
</head>
<!-- Attaching the view to the MyController -->
<body ng-controller="MyController">
<h1>{{author[0].name}}</h1>
<p>{{author[0].title+ ', '+author[0].company}}
See this snippet or correct the code on JS fiddle?
var myApp = angular.module("myApp", []);
myApp.controller("MyController", function ($scope){
$scope.author = {
'author': 'Ravy VIllalbobs',
'title': 'Staff Author',
'company': 'Lynda.com',
};
}
<div ng-controller="MyController">
<h1>{{author.name}}</h1>
<p>{{author.title+ ', '+author.company}}
</div>
$scope.author is an Object so you don't need to specify index in brackets here
<h1>{{author.name}}</h1>
<p>{{author.title+ ', '+author.company}}
updated fiddle
I am learning angular.. I have tried to run a small example through pluralsight, but wasn't able to render correct output..
http://plnkr.co/edit/cYEDSW3FrAKeh1SBjUVN?p=preview
HTML
<!DOCTYPE html>
<html ng-app>
<head>
<script data-require="angular.js#*" data-semver="1.3.7" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{text}}</h1>
<div>
<div>First name: {{person.firstName}}</div>
<div>Last name: {{person.lastName}}</div>
<img ng-src="person.imageSrc" title="{{person.firstName}} {{person.lastName}}">
</div>
</body>
</html>
script.js
var MainController = function($scope) {
var person = {
firstName: "Ajay",
lastName: "Sattikar",
imageSrc: "http://odetocode.com/Images/scott_allen_2.jpg"
};
$scope.text = "Hello Angular!";
$scope.person = person;
};
I am not able to figure out why angular variables are getting displayed as normal text instead of its assigned value. Experts, kindly help...
There are a few things that need to be changed in your code
you need to create an angular module
var app = angular.module('app', []);
2 add directive to html element
<html ng-app='app'>
need to register MainController against angular module like this:
app.controller('MainController', function($scope) {
var person = {
firstName: "Ajay",
lastName: "Sattikar",
imageSrc: "http://odetocode.com/Images/scott_allen_2.jpg"
};
$scope.text = "Hello Angular!";
$scope.person = person;
});
Here is a working demo - http://plnkr.co/edit/i9N2OC75EGZwUTDcKtLB?p=preview
You missed a few steps:
1. Declaring your app
<html ng-app='myApp'>
2. Declaring your controller inside your app module:
angular.module('myApp', [])
.controller('MainController', function($scope) {
var person = {
firstName: "Ajay",
lastName: "Sattikar",
imageSrc: "http://odetocode.com/Images/scott_allen_2.jpg"
};
$scope.text = "Hello Angular!";
$scope.person = person;
})
I am new to angular and I am trying to build my first directive, but it's not rendering inside my HTML.
Here is my HTML page : the directive is called at the bottom of the HTML
<!DOCTYPE html>
<html ng-app="store">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="storeController as store">
<ul class="list-group">
<li class="list-group-item" ng-repeat="product in store.product">
<h3 >
<product-name></product-name>
</h3>
</li>
</ul>
</body>
</html>
And here is my app.js :
(function(){
var app = angular.module("store",[]);
var gem = [
{
name: "Dodec",
price: 2.95,
canPurchase: true,
soldOut: false,
reviews: []
},
{
name: "Panta",
price: 20.4,
canPurchase: true,
soldOut: false,
reviews: []
}
];
app.controller("storeController",function(){
this.product = gem;
});
app.controller("tabController",function($scope){
$scope.tab = 1;
$scope.SetTab = function(value){
$scope.tab = value;
};
$scope.IsSet = function(value){
return value === $scope.tab;
}
});
app.controller("ReviewController", function($scope){
$scope.review = "";
$scope.addReview = function(product){
product.reviews.push($scope.review);
$scope.review = "";
};
});
app.directive("productName",function(){
return {
restrict : "E",
templateUrl : "product-name.html"
};
});
})();
notice the directive at the end.
And finally here is my product-name.html file :
{{product.name}}
<em class="pull-right"> {{product.price | currency}}</em>
What did I do wrong? why is the directive not behaving like it should?
Thanks
In product-name.html, AngularJS directive templates must have one root element.
I wrapped the html in divs in this plnkr.
<div>
{{product.name}}
<em class="pull-right"> {{product.price | currency}}</em>
</div>
The problem was with my server, I downloaded the http server from here https://github.com/nodeapps/http-server then started it and the directive shows up now.