I'd like to put angular variable in confirm message. After many tries, any solution doesn't work for me:
<a onclick="return confirm('Do you want to manage ' + {{item.name}} + ' with ...?')"
ng-href="/link={{item.ipAddress}}">{{item.name}}</a>
Can anybody help? (Works fine without {{item.name}} in confirm message)
If you're using Angular framework, I would suggest you to use (click) directive.
Then you can use a method defined in the controller linked to the template.
Demo
Component
confirm(item): void{
confirm(`Do you want to manage ${item.name} with...?`);
}
Template
<ul>
<li *ngFor="let item of items" (click)="confirm(item)">{{item.name}}</li>
</ul>
You can access the scope without changing the controller code. You just need to add an id to your controller. Here is what it will look like:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.item = {
"name": "NAME"
}
});
<!DOCTYPE html>
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-controller="myCtrl" id="ctrl1">
<a onclick="confirm('Do you want to manage ' + angular.element(document.getElementById('ctrl1')).scope().item.name + ' with ...?')">
{{item.name}}
</a>
</div>
</body>
</html>
As per my understanding of the question, I am writing the best solution as per me, which can help you resolve the issue.
var app = angular.module("app", []);
app.controller("MainController", function($scope, $window) {
$scope.item = {
"name": "Ronit Mukherjee",
"ipAddress": "192.197.85.39"
}
$scope.myFunc = function(name, ipAddress) {
if (confirm("Do you want to manage " + name + " with ...?")) {
$window.location.href = "/link=" + ipAddress;
}
}
});
a {
color: red;
text-decoration: underline;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app="app">
<div ng-controller="MainController">
<a ng-click="myFunc(item.name,item.ipAddress)">{{item.name}}</a>
</div>
</body>
</html>
If you still face any issue, then feel free to comment and clear the doubts.
Related
I have the following code:
app.controller('MatrixExpertCtrl', function($scope,$http){
$scope.PassedMatrix=[];
$scope.GetMatrixFromServer=function(){
$http.get("http://localhost:3000/getmatrixfromdb").success(function(resp){
alert("The matrix grabbed from the server is: " + resp[0].ans);
$scope.PassedMatrix.push(resp[0].ans);
});
};
$scope.DispSize=function(){
alert("testing");
alert("The size is "+$scope.PassedMatrix[0].size) ;
};
//$scope.GetMatrixFromServer();
});
Now, suppose, in HTML, I have something like this:
<div class="col-sm-3 col-md-3 col-lg-3">
<div class="text-center">
<h3>Example Survey</h3>
<p>example paragrah</p>
<p>More random text</p>
<p>ending the paragraphs</p>
<button id="updmat" ng-click="DispSize();" type="button" class="btn btn-default">Updates</button>
</div>
//Much more code
<div id="body2">
<div class="col-sm-6 col-md-6 col-lg-6" style="background-color:#ecf0f1;">
<div ng-controller="MatrixExpertCtrl" ng-app="app" data-ng-init="GetMatrixFromServer()">
<div class="text-center">
Meaning with this:
Is it possible to call a function that is defined inside a controller, from outside of the scope of that same controller?
I need this because the function is manipulating a shared object, owned by the controller in a very very simple fashion (for example, clicking on the button changes the color of a given element).
I am having trouble to make this work, any help will be appreciated.
I think that declaring some data structures as global would help me solving this problem, but, I would like to avoid doing that because, besides it being bad practice, it might bring me more problems in the future.
If i understand your problem correctly than what you basically do have is one utility function which will work on your shared object and do your useful things (i.e. clicking on the button changes the color of a given element) and now you do require the same behaviour in another controller outside of it's scope. You can achieve the same thing in 2 different ways :
1).Create a service and make it available in your controllers like this :
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
changeColour: function() {
alert("Changing the colour to green!");
}
};
});
myApp.controller('MainCtrl', ['$scope', 'myService', function($scope,
myService) {
$scope.callChangeColour = function() {
myService.changeColour();
}
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="callChangeColour()">Call ChangeColour</button>
</body>
</html>
Pros&Cons: More angularistic way, but overhead to add dependency in every different controllers and adding methods accordingly.
2).Access it via rootscope
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.globalChangeColour = function() {
alert("Changing the colour to green!");
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="globalChangeColour()">Call global changing colour</button>
</body>
</html>
Pros&Cons: In this way, all of your templates can call your method without having to pass it to the template from the controller. polluting Root scope if there are lots of such methods.
try removing semicolon
ng-click="DispSize()"
because it binds ng-click directive to the function.
pls, help me with next question
I try to implement conditional classes on div blocks using ng-class but have encountered next problem - "it is not working". Example seems to be very simple, I even do not know how else it can be described.
But one more idea - controller does not working instead of ng-class.....i do not know.
Here you can see my code pls, probably you will find smth wrong or give me an advice.
http://plnkr.co/edit/Zm0g4QfkqzTD3h4FWfcp?p=preview
demoApp = angular.module('demoApp',[]);
var controllers = {};
controllers.testCntr = function ($scope)
{
$scope.setClass = function()
{
alert('works');
return True;
}
};
HTML
<!doctype html>
<html ng-app="demoApp">
<head>
<title></title>
<style>
.red
{
color:red;
}
</style>
<script src="angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route.js"></script>
</head>
<body>
<div ng-controller="testCntr">
<span ng-class="{red: $scope.setClass()}">Test color</span>
<div>{{$scope.setClass()}}</div>
</div>
</body>
</html>
Thanks for your amendments.
Several problems here.
You can only add one controller at a time with .controller()
In your template, $scope is already the context, so don't include it in the HTML
True should be true
You are missing an ng-app directive
angular.js is not included properly
Your scripts.js is not included
Here's a working version of your Plunkr with the changes above: http://plnkr.co/edit/ybDScjDrrIkH8tBNfIg1?p=preview
When you call a function which is in the scope from the view, just call it like that :
<body ng-app="app">
<div ng-controller="Ctrl">
<span ng-class="{'red': setClass()}">Test color</span>
<div>{{setClass()}}</div>
</div>
</body>
Here the Working Plunkr
You should create an app.js services.js and controllers.js
Your controller should be moved to the controllers.js and look a little something like this.
demoApp.controller('testCntr',function ($scope){
$scope.setClass = (function(){
alert('works');
return True;
})
});
To add the controller to your app you should do this
demoApp.controller('testCntr', function ($scope) {
$scope.setClass = function() {
alert('works');
return True;
}
})
Working Plunkr: http://plnkr.co/edit/LPY94jPJdIJX4pr9K5FY?p=preview
Working Demo:
demoApp = angular.module('demoApp',[]);
demoApp.controller('testCntr', function ($scope) {
$scope.setClass = function() {
alert('works');
return 33;
return True;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" <div="" ng-controller="testCntr">
<span ng-class="{red: $scope.setClass()}">Test color</span>
<div>{{setClass()}}</div>
</div>
your script.js file should be
var app = angular.module('demoApp',[]);
app.controller('testCntr', ['$scope', function($scope) {
$scope.setClass = function() {
return true;
};
}
]);
and html:
<!DOCTYPE html>
<html ng-app="demoApp">
<head>
<script src="angular.min.js"></script>
<script src="script.js"></script>
<style>
.red {
color:red;
}
</style>
</head>
<body ng-controller="testCntr">
<span ng-class="{red: setClass()}">Test color</span>
</body>
</html>
It may solve your problem
Plunker link: http://plnkr.co/edit/Ftx3M0aG9G8cJtyrn5wj?p=preview
I'm new to Angular JS.
I have a few questions. Scope seems to be working with my first controller testController but not with my second controller controlspicy.
Why is not letting me print out $scope.greeting ? Shouldn't the binding work because I assigned a controller.
Here's a plunkr link which directs straight to the code.
http://plnkr.co/edit/NbED8vXNiZCqBjobrISa?p=preview
<!DOCTYPE html>
<html ng-app="newtest">
<head>
<script data-require="angular.js#*" data-semver="1.3.5" src="https://code.angularjs.org/1.3.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script src="spicy.js"></script>
</head>
<body ng-controller="testController">
<h1>Hello Plunker! {{message}}</h1>
<input type="text" name="firstName" ng-model="thetext">
{{double(thetext)}}
<h1 ng-controller="controlspicy">new test</h1>
<h2>{{greeting}}</h2>
</body>
</html>
script.js
var app = angular.module("newtest", [])
.controller("testController", ["$scope", function($scope) {
$scope.message = "hola";
$scope.double = function(value){
if (value == null){
return 0;
}
return value*2;
};
}]);
spicy.js
var appl = angular.module("thespicy", [])
.controller("controlspicy", ["$scope", function($scope){
$scope.greeting = "hello";
}]);
As previously mentioned by Preston you need to wrap the <h2> inside a tag with ng-controller. There is one more issue however.
controlspicy is defined in another module than the one you specify in ng-app.
Change angular.module("thespicy", []) in spicy.js to angular.module("newtest").
You should almost never use more than one module in one app. You could however divide it into different sub-modules but if your new to Angular I would recommend using just one module to start with.
To clarify; you should only define a module once by typing angular.module("module_name", []). Notice the [] here. In this array you would put dependencies for the module (if you really wanted the 'thespicy' module you could have included it as a dependency with angular.module("newtest", ['thespicy']). If you later wanted to add a controller to the module you would reference the module with angular.module("module_name") (no []). For example:
// Define a module
angular.module('foo', []);
// Reference the previously defined module 'foo'
angular.module('foo')
.controller('barCtrl', function() { ... });
Here is a working fork of your example: http://plnkr.co/edit/rtUJGeD52ZoatoL3JgwY?p=preview btw.
The nested controller only controls inside the scope of the tag. In this case, it only has access to the scope inside of the h1 tag.
Try this:
<!DOCTYPE html>
<html ng-app="newtest">
<head>
<script data-require="angular.js#*" data-semver="1.3.5" src="https://code.angularjs.org/1.3.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script src="spicy.js"></script>
</head>
<body ng-controller="testController">
<h1>Hello Plunker! {{message}}</h1>
<input type="text" name="firstName" ng-model="thetext">
{{double(thetext)}}
<div ng-controller="controlspicy">
<h1>new test</h1>
<h2>{{greeting}}</h2>
</div>
</body>
</html>
Here's a working plunker of your example: http://plnkr.co/edit/gufbBI4i68MGu8FWVfJv?p=preview
I should point out that you didn't include your controller in your main app.
script.js should start like this:
var app = angular.module("newtest", ['thespicy'])
You have multiple apps
check this plunkr for working nested controllers
<div>
<div ng-controller="testController">
<h1>Hello Plunker! {{message}}</h1>
<input type="text" name="firstName" ng-model="thetext">
{{double(thetext)}}
</div>
<div ng-controller="thespicy">new test
<h2>{{greeting}}</h2>
</div>
</div>
script.js
var app = angular.module("newtest", [])
.controller("testController", ["$scope", function($scope) {
$scope.message = "hola";
$scope.double = function(value){
if (value == null){
return 0;
}
return value*2;
};
}])
.controller('thespicy', ["$scope", function($scope) {
$scope.greeting = "Hello";
}])
I'm learning how to develop with AngularJS for the first time for a class and I am trying to understand why I'm not getting an updated value of the length property and was hoping someone could help me understand why my code is not working and what I should be doing for it to update.
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<title>Grocery List</title>
<script src="js/angular.min.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app>
<h1>My Grocery List</h1>
<div ng-controller="MYController">
<input type="text" ng-model="listItem" placeholder="Add Grocery Item" />
<input type="submit" ng-click="addItem()" value="Save" />
<h2>Items</h2>
<ul ng-show="itemArray.length">
<li ng-repeat="listItem in itemArray">
{{ listItem }}
<buton ng-click="deleteItem(listItem)">X</buton>
</li>
</ul>
</div>
</body>
</html>
Code in app.js
function MYController($scope) {
$scope.listItem;
$scope.itemArray = [];
$scope.addItem = function() {
$scope.itemArray.push($scope.listItem);
$scope.listItem = '';
}
$scope.deleteItem = function(deletedItem) {
var idx = $scope.itemArray.indexOf(deletedItem);
$scope.itemArray.splice(idx, 1);
}
}
In Angular when you make controller then it need to assign with a module
So here you will made your controller in js like below
angular.module('todoApp', [])
.controller('MYController', ['$scope', function($scope) {
$scope.listItem;
$scope.itemArray = [];
$scope.addItem = function() {
$scope.itemArray.push($scope.listItem);
$scope.listItem = '';
}
$scope.deleteItem = function(deletedItem) {
var idx = $scope.itemArray.indexOf(deletedItem);
$scope.itemArray.splice(idx, 1);
}
});
And in HTML bootstrap angular like below in body tag and use your controller
<body ng-app="todoApp">
See here for reference https://angularjs.org/#add-some-control
I think there may be some confusion between the listItem in ng-model="listItem" and ng-repeat="listItem in itemArray". Try changing the second one to a different variable name like this:
<li ng-repeat="item in itemArray">
{{ item }}
<button ng-click="deleteItem(item)">X</button>
</li>
Also, change that first line in your controller $scope.listItem; to $scope.listItem = '';.
assign module to angular app using this code:
var app = angular.module('plunker', [])
and
<html ng-app="plunker">
see plunker
I have just begun trying to integrate ngRoute into an application I am building, but am having trouble getting ngRoute to work.
I have created a simple app to describe my attempt.
index.html:
<!DOCTYPE html>
<html ng-app="tester">
<head>
<meta charset="utf-8" />
<title>ngRoute Test</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular-route.js"></script>
<script src="app.js"></script>
</head>
<p>Here is a link to switch views:</p>
Test
<div ng-view></div>
</html>
app.js
var app = angular.module('tester', ['ngRoute']).config(function($routeProvider) {
$routeProvider
.when('/tests', {
templateUrl: 'tests.html',
controller: 'TestCtrl'
});
});
app.controller('TestCtrl', ['$scope', function($scope){
$scope.title = "This is a Test Page";
}]);
tests.html
<p>{{ title }}</p>
Here is a plunkr that shows my attempt: http://plnkr.co/edit/ntgV5xFTl46tBugEnCVe?p=preview. Any help on this issue would be much appreciated!
Since you don't have the Html5 Mode enabled you need to make the link to the view like this:
Test
Check this plunker: http://plnkr.co/edit/Pn4rzbFSxcjyfeojJyF1?p=preview