I am a beginner in angularjs and currently I am facing an issue with ng-include.
I have a test app using partials.
Here is my code.
<html ng-app ="TextboxExample">
<head>
<title>Settings</title>
<script src="angular.js"></script>
</head>
<body ng-controller="ExampleController">
<div ng-include src = "'view.html'"></div>
<script>
angular.module('TextboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.textboxVal = 'fddfd';
$scope.ReadGeneralSettings = function() {
alert($scope.textboxVal);
}
$scope.ResetGeneralSettings = function() {
$scope.textboxVal = 'fddfd';
}
}]);
</script>
<button class="pull-right" ng-click = "ReadGeneralSettings()">Read</button>
<button class="pull-right" ng-click = "ResetGeneralSettings()">Cancel</button>
</body>
</html>
The partial code view.html is
<input type="text" ng-model="textboxVal">
For some reason, textboxVal set to ng-model doesn't get updated when I enter the value in the text box.
But this works fine if I don't use ng-include and directly add the content of view.html into the main html file.
Please help.
Thanks
Sunil
Use $parent to access the scope of the controller
Demo
<input type="text" ng-model="$parent.textboxVal">
The problem is that ngInclude creates new scope, so the model you define inside partial template with ngModel works with local scope value, and outer ExampleController can't see it.
The simple solution is to use prototypical chain of scope objects, then inner scope will inherit and use model value from the outer scope:
<body ng-controller="ExampleController">
<div ng-include src = "'view.html'"></div>
<script>
angular.module('TextboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.model.textboxVal = 'fddfd';
$scope.ReadGeneralSettings = function() {
alert($scope.model.textboxVal);
}
$scope.ResetGeneralSettings = function() {
$scope.model.textboxVal = 'fddfd';
}
}]);
</script>
<button class="pull-right" ng-click = "ReadGeneralSettings()">Read</button>
<button class="pull-right" ng-click = "ResetGeneralSettings()">Cancel</button>
</body>
and then use it in partial as
<input type="text" ng-model="model.textboxVal">
Related
I want to execute a ng-include and show the content only after a button is clicked. I tried to use the ng-if directive and show the div when the ng-model is true, but his value is not changed in the myFunctionfunction.
<div ng-controller='myCtrl'>
<div ng-if='include==true' ng-include='"path"'></div>
<input type="button" ng-click='myFuntion()'/>
</div>
.controller('myCtrl', function($scope){
$scope.include = false;
$scope.myFunction = function(){
$scope.include = true;
}
})
There is a typo in your ng-click function. myFuntion should be myFunction. You can also just use ng-if='include' instead of ng-if='include==true'.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.include = false;
$scope.myFunction = function(){
$scope.include = true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-if='include'>Clicked</div>
<input type="button" ng-click='myFunction()'/>
</div>
I would simply create a function that change the variable path for a valid one, no need to do a ng-if
$scope.myFunction = function(newPath){
$scope.path = newPath;
}
<div ng-include="path"></div>
<input ng-click="myFunction('path/to/file.html')" type="button />"
I am rendering HTML text in a div, which I make then editable. The user can modify the text, but is there a way to get back the text modified in HTML?
This is the fiddle I am trying to make working:
<div ng-controller="MyCtrl">
Hello, {{name}}!
<div class="editable" ng-bind-html="documentBody"></div>
</div>
Controller:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.name = 'Superhero';
$scope.documentBody = '<p align="center"><font size="2">Ciao</font></p><br><p align="center"><font size="2">Bello!</font></p>';
$('.editable').each(function () {
this.contentEditable = true;
});
}
http://jsfiddle.net/sirfabio80/5sr8wnzv/
Thanks in advance
Fabio
Use directive like below. We can't edit like you expect, We must use ng-model with some kind of simple way.
var myApp = angular.module('myApp',['ngSanitize']);
myApp.controller('MyCtrl',function ($scope, $sce) {
$scope.name = 'Superhero';
$scope.names = [{name:"Ciao"},{name:"Bello"},{name:"Allo"}];
});
myApp.directive('dirNew', function(){
return {
restrict:"EA",
scope:{repeats:"=",},
template:'<p align="center" ng-repeat="n in repeats"><span size="2" ng-click="click($index)" ng-hide="n.enabled">{{n.name}}</span><input type="text" ng-show="n.enabled" ng-model="n.name"><button ng-show="n.enabled" ng-click="click($index)">Ok</button></p><br>',
link: function(scope) {
scope.click = function(index){
scope.repeats[index].enabled = !scope.repeats[index].enabled;
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-sanitize.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">{{names}}
<br>
Hello, {{name}}!<br>
Click the text and Edit......
<dir-new repeats="names"></dir-new>
</div>
</body>
Hi I am new to angular and I am trying to create 2 apps in a single HTML file but I am not getting the output for the second app and I am getting the proper output for the first app. Can anyone tell me where am I doing it wrong? The code is as below
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>The example for angular</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<style>
input.ng-invalid {
background-color: lightcyan;
}
</style>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="hello">
<p>{{firstname}}</p>
</div>
<div ng-init="Akshay=[
{firstname:'Sandeep',place:'mangalore'},
{firstname:'sirish', place:'haridwar'},
{firstname:'krish', place:'mathura'}]">
<div ng-repeat="name in Akshay">
{{name.firstname + ' ' + name.place}}
</div>
</div>
<div class="ang"></div>
<form name="myForm">
<input type="email" name="emaild" ng-model="text">
<span ng-show="myForm.emaild.$error.email">Please enter the proper email</span>
</form>
<input type="text" ng-model="mytext" required>
</div>
<div ng-app="Appname" ng-controller="personCtrl">
<input type="text" ng-model="firstName">
<input type="text" ng-model="lastName">
<p>His firstname was{{firstName}}</p>
<p>His second name was {{lastName}} </p>
<h1> His name was {{fullname()}} </h1>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("hello", function ($scope) {
$scope.firstname = "Akshay";
});
app.directive("ang", function () {
return {
restrict: "C",
template: "This is a great time to be alive"
};
});
var appsec = angular.module('Appname', []);
appsec.controller("second", function ($scope) {
$scope.firstName = "Bhagath";
$scope.lastName = "Singh";
$scope.fullname = function () {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>
</body>
</html>
you can't bootstrap two module in single html file. According to Doc
Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead. AngularJS applications cannot be nested within each other
you can use manual bootstrap method to bootstrap both the modules simultaneously
Modify the two boostrap lines to happen when the document is ready:
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById('app1'), ['app1']);
angular.bootstrap(document.getElementById('app2'), ['app2']);
});
When modifying your plnkr in this way, both apps started working properly.
Live Demo : https://jsfiddle.net/samirshah1187/w7gv56t5/
As #Samir said, we can use manual bootstrap method to bootstrap both the modules simultaneously we need to define id like this <div ng-app="myApp" id="myId"> <div ng-app="Appname" ng-controller="personCtrl" id="personId">,
and then add these lines at the end inside script
angular.bootstrap(document.getElementById('myId'), ['myApp']);
angular.bootstrap(document.getElementById('personId'), ['Appname']);
we need to bootstrap the modules to have multiple ng-app within the same page.
I asked this question but the specific question I'm asking has changed dramatically.
I have a piece of code:
<div ng-attr-controller="{{pings || 'PingsCtrl as pings' }}">
<h1 ng-click="pings.press()">asdf</h1>
</div>
This code is injected into two html pages. One page already calls PingsCtrl. The other doesn't. I'm really trying to keep this code DRY and I only want to have one reference of the code above.
How can I write the code above to generate ng-controller if PingsCtrl hasn't already instantiated.
Here are the two html pages.
HTML
// First page
<html ng-app="coolApp">
<div ng-controller="PingsCtrl as pings">
<div ng-attr-controller="{{pings || 'PingsCtrl as pings' }}">
<h1 ng-click="pings.press()">asdf</h1>
</div>
</div>
</html>
// Second page
<html ng-app="coolApp">
<div ng-attr-controller="{{pings || 'PingsCtrl as pings' }}">
<h1 ng-click="pings.press()">asdf</h1>
</div>
</html>
Javascript is here:
angular.module('coolApp', [])
.controller('PingsCtrl', function() {
var vm = this;
vm.press = function() {alert(123)};
})
What's wrong and how do I fix this?
Just use a service. It's really the intended structure for having common data and functionality between pages.
Part of the problem with what you were attempting is, whether or not you manage to preserve the controller, Angular has its own management that won't follow you with that, and will be refreshing components without you. You'll run into things like a $scope that doesn't actually match the page you're looking at, and it ends up causing more problems than it's worth.
I do have a solution but I also echo other people's concerns about the approach. You may want to have a global controller that you drop on the body for things that can happen anywhere and in most of the other controllers and just call through that. Eg
<body ng-controller="GlobalCtrl as gc">
<h1 ng-click="gc.pingPress()"></h1>
</body>
Anyway here is what I came up with.
<div ng-if="pings">
<h1 ng-click="pings.press()">asdf</h1>
</div>
<div ng-if="!pings">
<div ng-controller="PingsCtrl as pings">
<h1 ng-click="pings.press()">asdf</h1>
</div>
</div>
This will work if it is dropped inside or outside of an existing PingsCtrl.
Here is a plunker.
https://plnkr.co/edit/4x0kSazcg0g0BsqPKN9C?p=preview
Please, check my solution to see how to share data between controllers
var app = angular.module('myApp', []);
app.controller("aCtrl", function ($scope, PingList) {
$scope.addPing = function() {
PingList.add('Ping A');
};
});
app.controller("bCtrl", function ($scope, PingList) {
$scope.addPing = function() {
PingList.add('Ping B');
};
});
app.factory('PingList', function () {
var pings = ['Ping1', 'Ping2'];
return {
add: function(ping) {
pings.push(ping);
},
get: function () {
return pings;
}
};
});
app.directive('pingList', function(PingList) {
return {
restrict: 'EA',
link: function($scope) {
$scope.pings = PingList.get();
$scope.press = function(ping) {
alert(ping);
}
},
template: '<ul><li ng-repeat="ping in pings" ng-click="press(ping)">{{ping}}</li></ul>'
};
});
a, li {
cursor: pointer;
}
a {
color: blue;
text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="aCtrl" style="float: left">
<a ng-click="addPing()">click to add A ping</a>
<ping-list></ping-list>
</div>
<div ng-controller="bCtrl" style="float: right">
<a ng-click="addPing()">click to add B ping</a>
<ping-list></ping-list>
</div>
<div style="clear: both"></div>
</div>
I was just doing this tutorial which makes a lot of sense - http://onehungrymind.com/angularjs-sticky-notes-pt-2-isolated-scope/. A fiddle provided is here: http://jsfiddle.net/simpulton/SPMfT/
It shows how to bind attributes to the parent controllers scope using #, =, &.
I wanted to change the fiddle to use "controller as syntax", but can't seem to get it to work, my fiddle is here - http://jsfiddle.net/SPMfT/304/
Any thoughts on why this wouldn't work?
View:
<div ng-controller="MyCtrl as ctrl">
<h2>Parent Scope</h2>
<input ng-model="ctrl.foo"> <i>// Update to see how parent scope interacts with component scope</i>
<br><br>
<!-- attribute-foo binds to a DOM attribute which is always
a string. That is why we are wrapping it in curly braces so
that it can be interpolated.
-->
<my-component attribute-foo="{{ctrl.foo}}" binding-foo="ctrl.foo"
isolated-expression-foo="ctrl.updateFoo(newFoo)" >
<h2>Attribute</h2>
<div>
<strong>get:</strong> {{isolatedAttributeFoo}}
</div>
<div>
<strong>set:</strong> <input ng-model="isolatedAttributeFoo">
<i>// This does not update the parent scope.</i>
</div>
<h2>Binding</h2>
<div>
<strong>get:</strong> {{isolatedBindingFoo}}
</div>
<div>
<strong>set:</strong> <input ng-model="isolatedBindingFoo">
<i>// This does update the parent scope.</i>
</div>
<h2>Expression</h2>
<div>
<input ng-model="isolatedFoo">
<button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
<i>// And this calls a function on the parent scope.</i>
</div>
</my-component>
</div>
JS:
var myModule = angular.module('myModule', [])
.directive('myComponent', function () {
return {
restrict:'E',
scope:{
/* NOTE: Normally I would set my attributes and bindings
to be the same name but I wanted to delineate between
parent and isolated scope. */
isolatedAttributeFoo:'#attributeFoo',
isolatedBindingFoo:'=bindingFoo',
isolatedExpressionFoo:'&'
}
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
this.foo = 'Hello!';
var self = this;
this.updateFoo = function (newFoo) {
self.foo = newFoo;
}
}]);
Thanks JoseM for the heads up. I've rewritten this fiddle using angular 1.2 and "controller as" syntax here: - http://plnkr.co/edit/nUXWrj4yzypaQmtJShl9?p=preview
Not sure where to start with issue with the previous version:
In 1.2 isolated scope variables can't be used directly in the DOM,
they have to be in the template of the directive.
I made sure mydata was an object to avoid prototypical inheritance issues.
When evaluating an attribute with # you have to make sure you pass it
inside {{}}.
var app = angular.module("drinkApp", []);
app.controller("AppCtrl", function($scope) {
this.ctrlFlavor = {
data: "blackberry"
}
var self = this;
this.updateFoo = function(newFoo) {
self.ctrlFlavor.data = newFoo;
}
})
app.directive("drink", function() {
return {
scope: {
isolatedBindingFoo: "=",
isolatedAttributeFoo: "#",
isolatedExpressionFoo: '&'
},
template: '<h2>Isolated Binding</h2><div>{{isolatedBindingFoo}}</div><input ng-model="isolatedBindingFoo"></input><br><h2>Isolated Attribute</h2><div>{{isolatedAttributeFoo}}</div><input ng-model="isolatedAttributeFoo"></input><h2>Isolated Expression</h2><input ng-model="isolatedFoo"></input><button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>'
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Video Embed</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link href="style.css" rel="stylesheet" />
<script data-semver="1.2.4" src="http://code.angularjs.org/1.2.3/angular.js" data-require="angular.js#1.2.x"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-app="drinkApp">
<div ng-controller="AppCtrl as drinkCtrl">
<h2>AppCtrl Scope</h2>
{{drinkCtrl.ctrlFlavor.data}}
<br>
<input type="text" ng-model="drinkCtrl.ctrlFlavor.data">
<div drink isolated-binding-foo="drinkCtrl.ctrlFlavor.data" isolated-attribute-foo="{{drinkCtrl.ctrlFlavor.data}}" isolated-expression-foo="drinkCtrl.updateFoo(newFoo)">
</div>
</div>
</div>
</body>
</html>