My angular controller is not working? - javascript

I m new in Anguar js .
I have created a controller and pass the data but my controller not working can u please help me .
My code is this
Angular code is
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
$scope.person=[
{name:"Raj", gender:"M"},
{name: "raja", gender:"M"},
{name:"sevitra" gender:"F"}
]
});
HTML
Code is
<body ng-app="myApp">
<div controller="myController">
<a href="javascript:void()">
<button>Add New Field</button>
</a>
<div class="advance-menu-wraper">
<ul>
<li>
{{"person[0].name"}} + {{"person[0].gender"}}
<div class="head-text">Field 1:</div>
<div class="description-text">
How many staff members are proficient in Oracla programing
</div>
</li>
<li>
<div class="head-text">Field 2:</div>
<div class="description-text">
<form name="addForm">
<textarea rows="2"></textarea>
<div class="send-btn">
<button>
<i class="fa fa-check">Submit</i>
</button>
</div>
</form>
</div>
</li>
</ul>
</div>
</div>
</body>
Demo link

Your expression won't work:
{{"person[0].name"}} + {{"person[0].gender"}}
yields: "{{"person[0].name"}} + {{"person[0].gender"}}" in your html.
The correct expression would be:
{{person[0].name + person[0].gender}}
Moreover you have an syntax error in your array. The last object misses a comma.
This is a working plunkr: http://plnkr.co/edit/R9ojp8TWd7AloRrlPlZh?p=preview

You need to use the ngController directive
change
<div controller="myController">
to
<div ng-controller="myController">

{name:"sevitra" gender:"F"} should be {name:"sevitra", gender:"F"}
controller="myController" should be ng-controller="myController"
{{"person[0].name"}} + {{"person[0].gender"}} should be {{person[0].name}} + {{person[0].gender}}

three things which need to be change that i can see
change the controller to
app.controller('myController', [ '$scope',function($scope) {
change the <div controller="MyController"> to <div ng-controller="MyController"
and in the {{ " Person[0].Name "}} and {{ " Person[0].gender "}} remove the quote marks so it becomes {{Person[0].Name}} and {{Person[]0.gender}}

Related

Create a new scope outside ng-repeat

The idea is how a list of texts can be modified by pressing the button next to the text. We can also apply it to the title text which is outside the list.
HTML:
<div ng-controller="TextController">
<div class="title">
<span>{{ text }}</span>
<button ng-click="edit()">Edit</button>
</div>
<ul>
<li ng-repeat="text in list">
<span>{{ text }}</span>
<button ng-click="edit()">Edit</button>
</li>
</ul>
</div>
JavaScript:
angular.module("app").
controller("TextController", function($scope) {
$scope.text = "hello";
$scope.list = [....]; // list of texts;
$scope.edit = function() {
this.text += " world";
};
});
I'm not sure if I wrote it the right way. However, everything works fine except the edit button in the title which is when I'm trying to edit the title only, it accidentally edits all text which is in its children scope.
What I'm trying to do is to give the title a new scope so that the button doesn't affect other texts because it isn't a parent of any scope.
Yeah What you are trying to do is right:
The {{text}} variable is bound to the same controller scope. so the edit button just updates that value which makes it to change everywhere
You should try to update $scope.list value:
When you updated the scope, the html will render.
$scope.edit = function() {
$scope.list[this.$index] += " world";
};
Please check the demo:
http://jsfiddle.net/Lvc0u55v/7050/
Why don't you use another variable name for ng-repeat(i have made second text => txt). It is better to have separate functions for updating list and text, but if you want, you can try
<div ng-controller="TextController">
<div class="title">
<span>{{ text }}</span>
<button ng-click="edit()">Edit</button>
</div>
<ul>
<li ng-repeat="txt in list">
<span>{{ txt }}</span>
<button ng-click="edit($index)">Edit</button>
</li>
</ul>
</div>
The view is passing $index of the array element:
$scope.edit = function(listIndex) {
if(listIndex) $scope.list[listIndex] += " world"
else $scope.text += " world";
};
You could create an "include" combined with an ng-template so that you get a new scope.
http://jsfiddle.net/pfeq0mwe/3/
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-include src="'myTemplate.htm'">
</div>
<ul>
<li ng-repeat="text in list">
<span>{{ text }}</span>
<button ng-click="edit()">Edit</button>
</li>
</ul>
<script type = "text/ng-template" id = "myTemplate.htm">
<div class="title">
<span>{{ text }}</span>
<button ng-click="edit()">Edit</button>
</div>
</script>
</div>
<div >
</div>

How to get parent's parent's parent's id in Angularjs

I have a problem. I need to know how to get grandparent's ID in AngularJS.
I need "{{parent}}" to become "grand-parent".
(it should be <div id="me-and-my-grand-parent">)
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
var pid = document.getElementsByClassName("i-am-a-child");
var pid = this.parentNode.id;
if (this.parentNode&&this.parentNode.id)
var pid=this.parentNode.id;
$scope.parent = var pid;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div id="grand-parent{{$index}}" ng-repeat="item in items">
<div>
<div>
<div id="me-and-my-{{parent}}" class="i-am-a-child">
</div>
</div>
</div>
</div>
</div>
My actual code
<li ng-repeat="project in projects" ng-class="{active: project.childToggle, '': !project.childToggle,hasChild: project.children.length > 0 }" ng-dblclick="childToggleCt(project)" id="project-{{$index}}">
<div class="project-overview">
<header class="clearfix flip-area">
<span ng-if="!project.inCart" class="status dropdown-button warning pull-left" id="id-{{ParentIdShow}}" data-intro="Status bar" data-position="right">Pending</span>
And for now JS was like tis :
$scope.ParentIdShow = function(obj)
{
alert(obj.target.parentNode.parentNode.parentNode.id);
}
The answer to these types of "parent of my parent of my parent of my..." is to use the controller as syntax. Read more about it here. In short, it lets you do stuff like
<div ng-controller="ctrl1 as first">
<div ng-controller="ctrl2 as second">
...
<div ng-controller="ctrlN as Nth">
<div ng-repeat="i in arr">
{{first.property}}
{{second.otherProperty}}
{{Nth.nProperty}}
Note how you dont need any parent calls.

AngularJS view not updating

I'm trying to make my first AngularJS application and I've run into a problem.
I have an input:
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
A button:
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
and an expression:
{{ activeUser }}
I want the text to change to whatever was typed in the input once the button is clicked. For that I have the following controller:
app.controller('View1Ctrl', ['$scope', function($scope) {
$scope.userNameLogin = "";
$scope.activeUser = "Test";
$scope.setActiveUser = function() {
$scope.activeUser = $scope.userNameLogin;
console.log($scope.activeUser);
};
}]);
The initial value "Test" is shown just fine and according to the console the value of "activeUser" is being changed correctly as well. But the text in the view stays the same.
I have seen similar questions where a $scope.$apply() was the answer, but if I add that after the console.log I get
"Error: [$rootScope:inprog] $apply already in progress".
What am I missing here?
EDIT:
I have noticed that If I put the input, button and expression in the same HTML file it all works fine. However my Input and button are in a navbar in index.html while the expression is in view1.html
This is the body of index.html:
<body ng-app="myApp.view1">
<nav class="navbar navbar-inverse navbar-fixed-top" ng-controller="View1Ctrl as view">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#/view1">Kwetter</a>
</div>
<div class="navbar-collapse collapse" >
<ul class="nav navbar-nav">
<li>Home</li>
<li>Profile</li>
</ul>
<form class="navbar-form navbar-right">
<div class="form-group">
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="password" class="form-control">
</div>
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
</form>
</div>
</div>
</nav>
<div id="pagewrapper" class="container">
<div ng-view></div>
<div>Angular seed app: v<span app-version></span></div>
</div>
and this is my view1.html
<div ng-controller="View1Ctrl as view">
<!-- row 1: welcome -->
<div class="row">
<div class="col-md-12 pull-left">
<image ng-src="{{ view.users[0].avatar }}"/>
<!-- If I put the button and input here it will work -->
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
{{ activeUser }}
</div>
</div>
<!-- row 2: main content -->
<!-- left the rest of the content out because it would just clutter the page -->
I tried placing the ng-controller in <div id="pagewrapper" class="container"> instead of the first div of view1.html, but that made no difference.
I think u have misplaced the button or textbox or expression,
note : these should be inside the ng-controller.
please try this, it will work
<html>
<head>
<script data-require="angular.js#*" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app">
<div ng-controller="View1Ctrl">
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
{{activeUser}}
</div>
<h1>Hello Plunker!</h1>
</body>
</html>
script.js code
var app = angular.module("app",[]);
app.controller('View1Ctrl', ['$scope', function($scope) {
$scope.userNameLogin = "";
$scope.activeUser = "Test";
$scope.setActiveUser = function() {
$scope.activeUser = $scope.userNameLogin;
console.log($scope.activeUser);
};
}]);
refer http://plnkr.co/edit/ixbByBQ9nGm4XEqEFi4t?p=preview
You have the properties directly on $scope and that is breaking the binding. Instead try:
app.controller('View1Ctrl', ['$scope', function($scope) {
$scope.userInfo = {
userNameLogin: "",
activeUser:"Test"
}
$scope.setActiveUser = function() {
$scope.uesrInfo.activeUser = $scope.userInfo.userNameLogin;
console.log($scope.activeUser);
};
}]);
and in your view:
{{userInfo.activeUser}}
From Egghead.io https://egghead.io/lessons/angularjs-the-dot
Within your code I can't see anything causing the problem. I made a fiddle, that shows that your code works:
http://jsfiddle.net/xxvsn8xs/
You need to declare the ng-appand the ng-controller of course, like in the fiddle, to let the app work at all.
Also, an view update might not occur, if setting the activeUser actually occurs outside of the angular scope, which might be within an external library or whatever. It is true, that these could be achieved by calling $scope.$apply() directly, but it is nor recommended, as the digest might already be in progress. This is the case in your code, as why you get the according error message.
Instead use angulars $timeout service with a callback and 0 delay, that applies the value to $scope.activeUser. $timeout will check, if a digest cycle is in progress and if not, will start one.
$scope.setActiveUser = function() {
$timeout(function () {
$scope.activeUser = $scope.userNameLogin;
console.log($scope.activeUser);
});
};
Don't forget to define $timeout in your controllers dependencies:
app.controller('View1Ctrl', ['$scope', '$timeout', function($scope, $timeout) {
Angular watches the variable you bind to $scope, but if you replace that variable Angular is not able to detect it. That's why $apply would be a suggestion.
Another suggestion is to bind the variable to a 'model' variable:
app.controller('View1Ctrl', ['$scope', function($scope) {
$scope.userNameLogin = "";
$scope.myData = { activeUser: "Test" };
$scope.setActiveUser = function() {
// Angular will pick up the change in the myData object, and will update all variables attached to it
$scope.myData.activeUser = $scope.userNameLogin;
console.log($scope.myData.activeUser);
};
}]);
view:
{{ myData.activeUser }}
Do you execute your application in Apache ? I'd the same issue when I was using file:// And I fixed my issue by using a localhost.
I put my navbar (containing the input and button) in a partial and made a new directive for it. Instead of placing the navbar in the index.html I put it in the individual partials and now it works fine. I suspect the problem had something to do with different scopes.
navbar html:
<a class="navbar-brand" href="#/view1">
Kwetter
<image id="navbar-image" src="src/kwetter_logo.png"/>
</a>
</div>
<div class="navbar-collapse collapse" >
<ul class="nav navbar-nav">
<li>Home</li>
<li>Profile</li>
</ul>
<form class="navbar-form navbar-right">
<div class="form-group">
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="password" class="form-control">
</div>
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
</form>
</div>
</div>
the directive:
app.directive('navbar', function() {
return {
restrict: 'E',
templateUrl: 'partials/navbar.html',
controller: 'View1Ctrl as view'
}
});
Then I just added <navbar></navbar> to every view where I want a navbar.
Thanks everyone, your help pushed me in the right direction.

angular expression working inside a script tag

How do I get an angular expression working inside a script tag... I am pretty new to this and need help?
Here is an example of my java script code:
<script id="modal-2.html" type="text/ng-template">
<div class="modal transparent">
<div class="card">
<i class="icon ion-ios7-close close-modal" ng-click="closeModal(2)"></i>
<div class="item item-divider">
{{card.title}}
</div>
<div class="item item-text-wrap">
{{card.details}}
</div>
</div>
</div>
</script>
Here is an example of my array:
.controller('TodoCtrl', function($scope, $ionicPopup, $timeout, $ionicModal, $ionicSideMenuDelegate) {
$scope.cardss =
{id:1, title:'Frank', src:'img/Frank.png',details:'This will be the products description!'},
{id:2, title:'Generali', src:'img/Generali.png',details:'This will be the products description!'},
{id:3, title:'John Lewis', src:'img/JohnLewis.png',details:'This will be the products description!'},
];
There is nothing special wrt use of AngularJS expressions inside partial templates.
As already said your model is actually array - so you'll have to iterate through the items using ng-repeat like this:
<ul>
<li ng-repeat="card in cards">
Card id: {{card.id}}
Card title: {{card.title}}
Card details: {{card.details}}
</li>
</ul>
Please see working JSFiddle example.
Here is an example how you can use your template:
<div ng-include src="'modal-2.html'"></div>
or use it with a button:
<button ng-click="currentTpl='modal-2.html'">Show Modal</button>
<div ng-include src="currentTpl"></div>
The expression in the template then works as is usual.
Here is an example.

angular nested ng-repeat failure

it's me again :)
I am still at the very beginning with angularJS and I have just encountered a problematic issue.
I've got an array with some data that I want to be rendered on the page that's why I use ng-repeat but I also need to include another ng-repeat in the previous one.
I have the general ng-repeat="dialog in dialogWindows" and lower in the DOM ng-repeat="input in dialog.inputs", but the second ngRepeat dousnt work and it reports no errors in the coonsole. can You help me please?
Here is the JS:
var antroApp = angular.module('antroApp', []);
function dialogWindows($scope){
$scope.dialogWindows = [
{id:0,
idName:"pigmentation",
number:"1",
name:"Pigmentation",
answer1:"Clear complexion",
answer2:"Semi-swarthy complexion",
answer3:"Swarthy complexion",
answer4:"",
answer5:"",
answer6:"",
inputs:[{id:0,a:"a1",answer:"a"},
{id:1,a:"a2", answer:"b"}],
}
];
}
antroApp.controller('antroApp', antroApp);
and here is my HTML:
<div ng-controller="dialogWindows">
<div ng-repeat="dialog in dialogWindows">
<div id="{{dialog.idName}}" class="bold abs">
<div class="questionContainer rel">
<div class="menu abs">
<ul class="menuList">
<li id="menuStart" class=" unbold">Start</li>
<li id="menuAbout" class=" unbold">About</li>
<li id="menuTech" class=" unbold">Technology</li>
<li id="menuContact" class=" unbold">Contact</li>
</ul>
</div>
<div class="questionHeader"><div class="textGradient unbold tgHeaderXY">{{dialog.number}}.{{dialog.name}}</div></div>
<div class="empty"> </div>
<div class="questionBody">
<div ng-repat="input in dialog.inputs">
<input type="radio" id="radio1" name="sex" value="male">
<label for="radio1" class="answer abs {{input.a}}">{{input.answer}}</label>
</div>
</div>
Next <i class="icon-arrow-right icon-white"></i>
<i class="icon-pencil tgHeaderIcon icon-3x abs"></i>
</div><!--/pigmentation-->
</div><!--/ng-repeat-->
</div><!--/ng-controller-->
Any help will be appreciated.Thanks
Just single mistake;
set <div ng-repeat="input in dialog.inputs">
instead <div ng-repat="input in dialog.inputs">
As a side note:
use <pre>{{input|json}}</pre> as basic debugger to detect the issue
see Fiddle
In your nested loop you have to use ng-repeat, instead of ng-repat. If you would strip off example markup from unnecessary garbage before posting question, you would probably find typo yourself.
Then, you're missing ng-app="antroApp" directive in example.
Then, controller is dialogWindows, not antroApp:
antroApp.controller('dialogWindows', dialogWindows);
Missing closing div, typo as per Nenad answer, same naming for App and Controller, same naming for controller and scope variable... ouch my mind hurts, anyways, here is the result at jsbin
EDIT: (as per minitech request)
this an alternative version, example in jsbin has unnecessary code in question removed
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
</head>
<body ng-app="myApp"> <!-- *myApp is antroApp app -->
<div ng-controller="myCtrl"> <!-- *myCtrl is dialogWindows ctrl -->
<div ng-repeat="dialog in data"> <!-- data is dialogWindows scope var -->
<div class="bold abs">
<div class="questionContainer rel">
<div class="menu abs">
<ul class="menuList">
<li id="menuStart" class=" unbold">Start</li>
<li id="menuAbout" class=" unbold">About</li>
<li id="menuTech" class=" unbold">Technology</li>
<li id="menuContact" class=" unbold">Contact</li>
</ul>
</div>
<div class="questionHeader">
<div class="textGradient unbold tgHeaderXY">{{dialog.number}}.{{dialog.name}}</div>
</div>
<div class="empty"> </div>
<div class="questionBody">
<div ng-repeat="input in dialog.inputs">
<input type="radio" id="radio1" name="sex" value="male" />
<label for="radio1" class="answer abs {{input.a}}">{{input.answer}}</label>
</div>
</div> Next <i class="icon-arrow-right icon-white"></i>
<i class="icon-pencil tgHeaderIcon icon-3x abs"></i>
</div><!--/questionContainer--> <!-- *missing div -->
</div><!--/pigmentation-->
</div><!--/ng-repeat-->
</div><!--/ng-controller-->
<script>
var App = angular.module('myApp', []); //*myApp is in use now
App.controller('myCtrl', ['$scope', //*myCtrl is in use now
function ($scope) {
$scope.data = [{
id: 0,
idName: "pigmentation",
number: "1",
name: "Pigmentation",
answer1: "Clear complexion",
answer2: "Semi-swarthy complexion",
answer3: "Swarthy complexion",
answer4: "",
answer5: "",
answer6: "",
inputs: [{
id: 0,
a: "a1",
answer: "a"
}, {
id: 1,
a: "a2",
answer: "b"
}]
}];
}]);
</script>
</body>
</html>

Categories

Resources