Using Two Controllers in a Single AngularJS App - javascript

Full source code can be found http://plnkr.co/edit/rQSg5eMhm9uc9dSWnWEU?p=preview
In the index.html file if I use only one controller at a time it works. That is if I use
<body>
<div id="inputExample" ng-app="AngularJSTestBedWebApp" ng-controller="AngularJSInputExampleController">
input example: <input type="text" ng-model="inputValue" /><br/>
This is the updated value: {{inputValue}}
</div>
</body>
or if I use
<body>
<div id="scopeExample" ng-app="AngularJSTestBedWebApp" ng-controller="AngularJSScopeExampleController">
{{understandingScope}}
</div>
</body>
It will also work. However if I use both controllers at the same time such as
<body>
<div id="scopeExample" ng-app="AngularJSTestBedWebApp" ng-controller="AngularJSScopeExampleController">
{{understandingScope}}
</div>
<div id="inputExample" ng-app="AngularJSTestBedWebApp" ng-controller="AngularJSInputExampleController">
input example: <input type="text" ng-model="inputValue" /><br/>
This is the updated value: {{inputValue}}
</div>
</body>
The second controller never gets used. {{inputValue}} never gets assigned a default value and also never updates when you type in the text box. It literally just says "{{inputValue}}" the entire time.
I'm sure this is probably something easy but I'm very new to AngularJS. Thanks in advance for any help.

The ng-app attribute should be placed at the root of the application. In your example that would be <body/> or <html/>
<body ng-app="AngularJSTestBedWebApp">
<div id="scopeExample" ng-controller="AngularJSScopeExampleController">
{{understandingScope}}
</div>
<div id="inputExample" ng-controller="AngularJSInputExampleController">
input example: <input type="text" ng-model="inputValue" /><br/>
This is the updated value: {{inputValue}}
</div>
</body>
Updated plnkr

Here a complete example of two applications in one html page and two conrollers in one application :
<div ng-app = "myapp">
<div ng-controller = "C1" id="D1">
<h2>controller 1 in app 1 <span id="titre">{{s1.title}}</span> !</h2>
</div>
<div ng-controller = "C2" id="D2">
<h2>controller 2 in app 1 <span id="titre">{{s2.valeur}}</span> !</h2>
</div>
</div>
<script>
var A1 = angular.module("myapp", [])
A1.controller("C1", function($scope) {
$scope.s1 = {};
$scope.s1.title = "Titre 1";
});
A1.controller("C2", function($scope) {
$scope.s2 = {};
$scope.s2.valeur = "Valeur 2";
});
</script>

Related

Angular Clicking on Text to show div tag

I was wondering how to accomplish this with Angular as it seems that ng-click is something to use, then ng-model seems like that could be used.
I want to click on Text and then have a div show its contents and it is not working
My fiddle https://jsfiddle.net/gdxwtoL7/
<div class="well" ng-controller="MyController">
<a class="btn btn-primary" ng-model="selMe" ng-click="handleAnchorClick()">Enter Address</a>
</div>
<br>
<br>
<div ng-if="selMe">
adfadf
</div>
simple module and controller
angular.module('myapp', []);
angular.module('myapp').controller('MyController', MyController)
function MyController($scope) {
}
You're not doing anything inside the ng-click function, and you have the ng-if outside of the controller linked to the variable inside it.
https://jsfiddle.net/gdxwtoL7/1/
HTML
<div class="well" ng-controller="MyController">
<a class="btn btn-primary" ng-click="handleAnchorClick()">Enter Address</a>
<br>
<br>
<div ng-if="selMe">
adfadf
</div>
</div>
JS
angular.module('myapp', []);
angular.module('myapp').controller('MyController', MyController)
function MyController($scope) {
$scope.handleAnchorClick = function () {
$scope.selMe = true
}
}
The controller has to be aware of the div you want it to show.
the ng-if is waiting for the value of the selme which you can alter from the controller.
The ng-model binds your data to your controller in adding two-way data binding.
I made a little enhancement to your code to toggle the div when the text is clicked multiple times.
https://jsfiddle.net/gdxwtoL7/2/
<div class="well" ng-controller="MyController">
<a class="btn btn-primary" ng-model="selMe" ng-click="handleAnchorClick(selMe)">Enter Address</a>
<br>
<br>
<div ng-if="selMe">
adfadf
</div>
</div>
angular.module('myapp', []);
angular.module('myapp').controller('MyController', MyController)
function MyController($scope) {
$scope.handleAnchorClick = function (selMe) {
$scope.selMe = !selMe
}
}
The ngModel directive binds an input,select, textarea (or > custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.
ngModel is responsible for:
Binding the view into the model, which other directives such as input, textarea or select require.
Providing validation behavior (i.e. required, number, email, url).
Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
Setting related css classes on the element (ng-valid, ng-invalid, ng-dirty, ng-pristine, ng-touched, ng-untouched, ng-empty, ng-not-empty) including animations.
Registering the control with its parent form.
The ngClick directive allows you to specify custom behavior when an element is clicked.
Note : we need ng-click to capture the event and manipulate the data stored in ng-model.
Here is simple code without the need of controller:
<div class="well">
<a class="btn btn-primary" href="" ng-click="show=true">Enter Address</a>
</div>
<br>
<br>
<div ng-show="show">
adfadf
</div>
As #MikeHughesIII already pointed out, outside of your controller you can't reach $scope variables.
I am adding a quick snippet made after Mike's answer for completeness sake, showing a show/hide (toggle) approach, where the function sets the visibility variable to the opposite of its current status (true or false) when the function is invoked.
Hope that helps to clarify the issue.
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.6.2" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<h1>Hello {{hello}}!</h1>
<a href ng-click="toggleDivVisibility()">Enter your address</a>
<br>
<textarea ng-if="visible" name="address" id="address" cols="30" rows="5"></textarea>
</div>
<script>
angular.module('myApp', []);
angular.module('myApp')
.controller('myController', myController);
function myController($scope) {
$scope.hello = "world";
$scope.visible = false;
$scope.toggleDivVisibility = function() {
$scope.hello = 'mondo';
$scope.visible = !$scope.visible;
}
}
</script>
</body>
</html>

How to pass HTML element into angularjs code?

I want to pass the html element into angularjs code. I have some html elements like data-form-selector='#linechart_general_form' and data-url="{% url 'horizon:admin:metering:samples'%}" I want to access these Html elements in angularjs code.
My html templates, what make to change in the following code so that its elements accessible to angularjs code.
<div class="info row detail">
<div class="col-sm-9 chart_container">
<div class="chart"
data-chart-type="line_chart"
data-url="{% url 'horizon:admin:metering:samples'%}"
data-form-selector='#linechart_general_form'
data-legend-selector="#legend"
data-smoother-selector="#smoother"
data-slider-selector="#slider">
</div>
<div id="slider"></div>
<div class="col-sm-3 legend_container">
<div id="smoother" title="Smoothing"></div>
<div id="legend"></div>
</div>
</div>
</div>
--Update-- I just reread your question. To access those ATTRIBUTES (not elements, they are values of an element) you can select the object with an identifier, then manipulate it's attributes, like so (jQuery example):
$('.chart').attr('data-form-selector', 'myNewValue');
You may need to re-initialize sopmething because of the databinding but that's where I'd start.
==================================
You need to create an angular app and controller first, then use the angularjs and ng-model directive to bind the element to a method in your controller, i.e.:
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
In this case, you'd be manipulating the $scope.firstName and $scope.lastName variables in js.
Courtesy W3Schools
http://www.w3schools.com/angular/angular_intro.asp
You can do a Directive for doing that.
https://docs.angularjs.org/guide/directive

Is there an angular directive that can restrict scope for an element in the DOM

Hi I was just wondering if there is some built-in angular directive (ng-some-directive) that allows you to restrict the scope to a particular model for the desired DOM element.
I belive I have seen something similar done before, but maybe I am thinking of knockout.js
<script>
angular.module('example', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.heading = 'Some Value';
$scope.complexModel = {...}
}]);
</script>
<div ng-controller="ExampleController">
<h1>{{ heading }}</h1>
<div ng-some-directive='complexModel.to.long.really.annoying'>
<input type='text' ng-model='variable' /> // Actually coming from complexModel.to.long.really.annoying.variable
</div>
</div>
This is a drastically simplified version
Though its not meant for it
<div ng-init='sn = complexModel.to.long.really.annoying'>
<input type='text' ng-model='sn' />
</div>

AngularJS Dynamic Template with indexed scope variable arrays

I'm using AngularJS and trying to create a form where I can dynamically add new inputs, similar to this fiddle: http://jsfiddle.net/V4BqE/ (Main HTML below, working code in fiddle).
<div ng-app="myApp" ng-controller="MyCtrl">
<div add-input>
<button>add input</button>
</div>
</div>
I would like to be able to use a HTML template for my form since the input I'm adding is ~300 lines long. My issue is I cannot figure out how to index the scope variable containing the data when used in a template. I've tried to make my own modified version of the above code on plnkr http://plnkr.co/edit/4zeaFoDeX0sGTuBMCQP2?p=info . However, when I click the button no form elements appear.
Online (plnkr) I get a 404 not found for my template.html, but I think that is just a plnkr limitation. On my machine with a Python HttpServer I get an Error: [$parse:syntax] for the $templateRequest and a TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. when using the $http.get method.
Any advice for getting the indexed scope variable array to work with an external html file?
Thanks, JR
Edit: Update plnkr link
You can do it without directive & external template
what you are trying to do does not require a directive (it actually much simple with the basic angularjs tools)
http://plnkr.co/edit/LVzGN8D2WSL2nR1W7vJB?p=preview
html
<body>
<div class="container" ng-app="myApp" ng-controller="MyCtrl">
<button class="btn btn-primary" type="button" ng-click="addPhoneInput()">add input</button>
<form>
<div ng-repeat="item in telephoneNumbers">
<hr>
<input type="text" ng-model="item.phone">
</div>
</form>
<hr>
<div class="well">
<h4>Phone Numbers,</h4>
<p ng-repeat="item in telephoneNumbers">{{item.phone}}</p>
</div>
</div>
</body>
js
var app = angular.module('myApp', []);
app.controller('MyCtrl', ['$scope', function($scope) {
// Define $scope.telephone as an array
$scope.telephoneNumbers = [];
$scope.addPhoneInput = function() {
$scope.telephoneNumbers.push({});
};
// This is just so you can see the array values changing and working! Check your console as you're typing in the inputs :)
$scope.$watch('telephoneNumbers', function(value) {
console.log(value);
}, true);
}]);
If you insist using a directive,
http://plnkr.co/edit/BGLqqTez2k9lUO0HZ5g1?p=preview
phone-number.template.html
<div>
<hr>
<input type="text" ng-model="ngModel" >
</div>
html
<body>
<div class="container" ng-app="myApp" ng-controller="MyCtrl">
<button class="btn btn-primary" type="button" ng-click="addPhoneInput()">add input</button>
<form>
<phone-number ng-repeat="item in telephoneNumbers" ng-model="item.phone"></phone-number>
</form>
<hr>
<div class="well">
<h4>Phone Numbers,</h4>
<p ng-repeat="item in telephoneNumbers">{{item.phone}}</p>
</div>
</div>
</body>
js
var app = angular.module('myApp', []);
app.controller('MyCtrl', ['$scope', function($scope) {
// Define $scope.telephone as an array
$scope.telephoneNumbers = [];
$scope.addPhoneInput = function() {
$scope.telephoneNumbers.push({});
};
// This is just so you can see the array values changing and working! Check your console as you're typing in the inputs :)
$scope.$watch('telephoneNumbers', function(value) {
console.log(value);
}, true);
}]);
app.directive('phoneNumber', function(){
return {
replace:true,
scope: {
ngModel: '=',
},
templateUrl: "phone-number.template.html"
}
});

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.

Categories

Resources