How to get the value of a custom attribute in angular js - javascript

I have created a custom attribute called test in angular js. When I write the test attribute just beside the ng-controller keyword i.d.
<div ng-controller="myCon" test="abc"></div> then I can access that test from the controller by using alert($attrs.test). But if I write the custom attribute test other than beside of the ng-controller keyword, I can't access that. i.e.
<div ng-controller="myCon">
<div test="def"></div>
</div>
In this case I got undefined in alert($attrs.test)
Full code...
<html>
<script src="angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="kumar" >
<button ng-click="check()" test="def">Click</button>
</div>
<script>
var app = angular.module("myApp", []);
app.directive("test", function() {
return {
//template : "<h1>Hello</h1>"
};
});
app.controller("kumar",function($scope,$attrs){
$scope.check=function(){
alert(JSON.stringify($attrs.test)); //getting undefined. I
//should get def.
}
});
</script>
</body>
</html>

app.directive("test", function() {
return {
restrict: "A",
scope: {
text: "#test"
}
};
});
Update your directive scope and add restrict . For better understanding refer to this question

You can check it:
<html>
<script src="src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js""></script>
<body ng-app="myApp">
<div ng-controller="kumar" >
<button ng-click="check()" test="def">Click</button>
</div>
<script>
var app = angular.module("myApp", []);
app.directive("test", function() {
return {
//template : "<h1>Hello</h1>"
};
});
app.controller("kumar",function($scope,$attrs){
$scope.check=function(){
var testa=$scope.test;
alert(JSON.stringify(testa)); //getting undefined. I
//should get def.
}
});
</script>
</body>
</html>

You can get the element on click if you pass $event in ng-click, i.e. ng-click="check($event)" and can get the attribute from $event.target.
Check fiddle : https://jsfiddle.net/ayusharma/xb63g9ca/
JS
app.controller('myCtrl', function($scope) {
$scope.clickMe = function(evt) {
console.log(evt.target.getAttribute('test'))
}
});
HTML
<div ng-controller="myCtrl">
<div ng-click="clickMe($event)" test="abc">Click on Me</div>
</div>

Related

AngularJS call compile after compiled

<!DOCTYPE HTML>
<html lang="en-US" ng-app="theapp">
<head>
<meta charset="UTF-8">
<title>asd</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script type="text/javascript">
var mainScope;
angular.module('theapp', []).controller('MainCtrl', function($scope, $injector) {
$scope.demo = "test123";
$scope.scopecomp = function(){
angular.element(document).injector().invoke(function ($compile) {
$compile(document.body)($scope);
});
}
mainScope = $scope;
});
function addDiv(){
var $newDiv = $('<div>{{demo}}</div>');
$(document.body).append($newDiv);
}
function comp(){
mainScope.comp();
}
</script>
</head>
<body ng-controller="MainCtrl" ng-change="comp();">
<h1>{{demo}}</h1>
<input type="text" id="compText" />
<button onclick="addDiv();">add</button>
<button ng-click="scopecomp();">compile with ng-click (works fine)</button>
<button onclick="comp();">compile with onlick (not working)</button>
</body>
</html>
I want to run the comp() function anywhere in my project. I tried button onclick,it didn't work but ng-click works fine. What is the problem ? Why onclick doesn't work ?
New : changeContent function added.
<!DOCTYPE HTML>
<html lang="en-US" ng-app="theapp">
<head ng-controller="MainCtrl as main">
<meta charset="UTF-8">
<title>asd</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script type="text/javascript">
angular.module("theapp", []).controller("MainCtrl", MainController);
MainController.$injector = ['$timeout'];
var vm;
function MainController($timeout) {
vm = this;
vm.post = null;
function loadStuff(){
$timeout(function() {
vm.post = {
title: "Post Title",
content: "Post Content"
};
}, 1000);
}
loadStuff();
}
function changeContent(){
vm.post.content = "<div>new content </div>";
}
</script>
</head>
<body ng-controller="MainCtrl as main">
<p ng-hide="main.post">Loading...</p>
<h3>{{main.post.title}}</h3>
<p>{{main.post.content}}</p>
<button onclick="changeContent();">change</button>
</body>
</html>
New bodyController()
function bodyController($scope, $injector) {
_bodyController = this;
$scope.title = "ttt";
$scope.content = "aaa";
$scope.comp = function(){
angular.element(document).injector().invoke(function ($compile) {
$compile(document.body)($scope);
});
}
myAPP.Run(function(){
$scope.title = globalOBJ.title;
$scope.content = globalOBJ.content;
$scope.comp();
});
}
You should change your '' to this:
<body ng-controller="MainCtrl" ng-model="demo" ng-change="comp();">
If you check the url from the first line of the error log: https://docs.angularjs.org/error/$compile/ctreq?p0=ngModel&p1=ngChange. The problem is explained:
Controller 'ngModel', required by directive 'ngChange', can't be
found! Description This error occurs when HTML compiler tries to
process a directive that specifies the require option in a directive
definition, but the required directive controller is not present on
the current DOM element (or its ancestor element, if ^ was specified).
To resolve this error ensure that there is no typo in the required
controller name and that the required directive controller is present
on the current element.
The directive 'ng-change' require a 'ng-model' to work properly, that is why you are getting an compile error.
Now your second question, "Why onclick doesn't work ?". You should never manipulate the DOM from the controller, if you have to do that use a directive. When you call "scopecomp()" from the ng-click that method is invoked from "within" the angular engine, it will fire an digest cycle which will process the "html" (it's more than that, I'm trying to keep it simple) and print what you expect, but when you add "{{demo}}" directly to the DOM, that variable will not be processed.
There is no need to change the DOM manually to do what you are looking for, check the snippet below. I simulated your "database request" with a timeout function.
angular.module("app", [])
.controller("MainController", MainController);
MainController.$injector = ['$timeout'];
function MainController($timeout) {
var vm = this;
vm.post = null;
function loadStuff() {
$timeout(function() {
vm.post = {
title: "Post Title",
content: "Post Content"
};
}, 1000);
}
loadStuff();
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MainController as main">
<p ng-hide="main.post">Loading...</p>
<h3>{{main.post.title}}</h3>
<p>{{main.post.content}}</p>
</div>
$FirebaseJS.Run(function(){
$scope.$apply(function(){
$scope.obj = globalOBJ;
});
});
Finally I got it.

Error in retrieving value of dynamic ng-model

I am working on a form having multiple radio button listings in which I will need to create dynamic ng-model for each of the radio button. I am being able to do that, but when same I am trying to retrieve in controller (USING the ng-model iteration with angular forEach loop) it seems model cannot be replicated with console.log. Anyone help?
HTML
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<p ng-repeat="x in dummy">
<input type="radio" name="{{x.name}}" id="{{x.id}}" ng-model="Ques[x.id]"><span>{{x.value}}</span>
</p>
<button ng-click="ok()">Click</button>
<script>
//module declaration
var app = angular.module("myApp",[]);
//controller
app.controller("myCtrl", function($scope){
$scope.dummy = [
{name:"name1",value:"red",id:"id1"},
{name:"name2",value:"blue",id:"id2"},
{name:"name3",value:"yellow",id:"id3"},
];
$scope.ok = function(){
angular.forEach($scope.dummy, function(val, key) {
console.log($scope.Ques.val.id);
});
}
});
</script>
</head>
</html>
The Angular model is a JavaScript object itself. Instead of looping through the object, you can output the entire object to the console like this:
console.log( JSON.stringify($scope.dummy) );
To make it more easy to read and span multiple lines for complex objects, just add these arguments to stringify:
console.log( JSON.stringify($scope.dummy, null, 2) );
It also looks like you need a little work on how you handle the Radio buttons, I'll leave that to the excellent odetocode blog/site:
http://odetocode.com/blogs/scott/archive/2013/06/25/radio-buttons-with-angularjs.aspx
The main problem is that you're inside ngRepeat and it creates a child $scope, so to make it work, you should use or the Dot Rule or controller-as-syntax, as below:
$scope.model = {};
Then in your view:
<label>
<input type="radio" id="{{x.id}}" value="{{x.value}}" ng-model="model.Ques[x.id]">{{x.value}}
</label>
See it working:
(function() {
'use strict';
angular
.module('myApp', [])
.controller("myCtrl", function($scope) {
$scope.dummy = [
{
"name":"name1",
"value":"red",
"id":"id1"
},
{
"name":"name2",
"value":"blue",
"id":"id2"
},
{
"name":"name3",
"value":"yellow",
"id":"id3"
}
];
$scope.model = {};
$scope.ok = function() {
// With your original code:
angular.forEach($scope.dummy, function(val, key) {
console.log($scope.model.Ques[val.id]); // <- note the syntax
});
// Or you can get all key / values stored in radio buttons:
/*for (var key in $scope.model.Ques) {
console.log('Key => ', key);
console.log('Value => ', $scope.model.Ques[key]);
}*/
}
});
})();
<!doctype html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<p ng-repeat="x in dummy">
<label>
<input type="radio" value="{{x.value}}" id="{{x.id}}" ng-model="model.Ques[x.id]">{{x.value}}
</label>
</p>
<button ng-click="ok()">Click</button>
</body>
</html>
For reference, check the #PankajParkar's answer.
Have a look at that.
<body ng-app="myApp" ng-controller="myCtrl">
<p ng-repeat="x in dummy">
<input type="checkbox" name="{{x.name}}" id="{{x.id}}" ng-model="Ques[x.id]" />
<label>{{x.name}}</label>
</p>
<button ng-click="ok()">Click</button>
<script>
//module declaration
var app = angular.module("myApp",[]);
//controller
app.controller("myCtrl", function($scope){
$scope.dummy = [
{name:"name1",value:"red",id:"id1"},
{name:"name2",value:"blue",id:"id2"},
{name:"name3",value:"yellow",id:"id3"},
];
$scope.Ques = {};
$scope.ok = function(){
angular.forEach($scope.dummy, function(val, key) {
console.log($scope.Ques[val.id]);
});
}
});

How to access iframe by id in AngularJS?

How can I get reference of the iframe element with AngularJS ?
<div>
<iframe id="myframe" ...>
</div>
mycontroller.$inject = ['$document'];
function mycontroller ($document) {
console.log($document.getElementById("myframe")); //always null
}
I can see the iframe, but the reference lookup always prints null. Why?
The $document service returns an array.
You should use it like his :
console.log($document[0].getElementById("myframe"));
Please, see the jsfiddled solution : https://jsfiddle.net/jjbw1z8j/2/
use this,
angular.element('#myframe');
or
console.log(angular.element('#myframe'));
In angular interaction with the DOM elements should be implemented in the directives.
For example jsfiddle.
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope) {
})
.directive('myFrame', function() {
return {
link: function(scope, elem) {
console.log('it`s your iframe', elem);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="ExampleController">
<div>
<iframe my-frame></iframe>
</div>
</div>
</div>

Using ng-click inside a tooltip

I'm using Angular Bootstrap UI and I have a working tooltip.
HTML:
<div ng-app="helloApp">
<div ng-controller="helloCtrl as hello">
<a tooltip-trigger="click" tooltip-placement="bottom" uib-tooltip-html="<h1 ng-click='hello.clickInsideToSeeTheWorld()'>Click again!</h1>">Click me to see the tooltip</a>
</div>
</div>
Javascript:
angular.module('helloApp', ['ui.bootstrap'])
.controller('helloCtrl', helloCtrl)
function helloCtrl() {
var vm = this;
vm.clickInsideToSeeTheWorld = function() {alert(123)}
}
When I open up the tooltip, ng-click doesn't work. No alert appears. I receive no errors in my console. This is because the HTML isn't compiled. How can I properly compile the tooltip html to get this to work?
Extending the previous answer: You can probably use
uib-tooltip-template
instead of
uib-tooltip-html
when you exploit the angular template cache.
I understand that you maybe do not want to create an external template.html, but you do not have to do so. Simply try:
var app = angular.module("test", ['ui.bootstrap']);
app.controller("testController", function($scope, $templateCache) {
$scope.clickInsideToSeeTheWorld = function() {
alert(123)
}
if (!$templateCache.get ('template.html')) {
$templateCache.put (
'template.html',
'<a ng-click="clickInsideToSeeTheWorld()">Click again!</a>'
);
}
});
and
<div ng-app="test" ng-controller="testController">
<p style="margin-top: 5em;" uib-tooltip-template="'template.html'" tooltip-popup-close-delay="3000" >
Click me to see the tooltip
</p>
Here's an external plunker as well:
https://plnkr.co/edit/Dsi69MQg4NfgOSI5ClFh?p=preview
I added uib-tooltip-template instead uib-tooltip-html and changed this to $scope.
index.html
<body>
<script>
var app = angular.module("test", ['ui.bootstrap']);
app.controller("testController", function($scope) {
$scope.clickInsideToSeeTheWorld = function() {
alert(123)}
});
</script>
<div ng-app="test" ng-controller="testController">
<p style="margin-top: 5em;" uib-tooltip-template="'template.html'" tooltip-popup-close-delay="3000" >
Click me to see the tooltip
</p>
</div>
</body>
template.html
<a ng-click="clickInsideToSeeTheWorld()">Click again!</a>
Here is working Plunker
Or Alternative solution is for you to compile code yourself and then assign it to tooltip html
var sc = scope.$new( true ); //scope for html
sc.hello = {} // assign your hallo object to new scope
var compiledHtml = $compile( '<h1 ng-click="hello.clickInsideToSeeTheWorld()">Click again!</h1>')( sc );
Then you can set tooltip html to compiledHtml.

Angular JS : Controller properties not shown in html

I'm new to Angular JS. Sorry for this simple question.
I have learnt something from this tutorial: http://courseware.codeschool.com/shaping-up-with-angular-js/Slides/level01-05.pdf
And I have tried an example. This is not working. http://jsfiddle.net/89wfv/1/
HTML:
<html ng-app="main">
<body>
<div ng-controller="con">
<div>{{con.desc}}</div>
<input type='button' ng-click='getDesc();' value='Get name' />
</div>
</body>
</html>
Script
(function() {
var app = angular.module("main", []);
app.controller("con", function() {
this.desc = "test description";
this.getDesc = function() {
alert(this.desc);
}
});
})();
Problem is showing description in div and alert description by click.
Thanks in advance.
you forgot controller as something
<div ng-controller="con as ctrl">
<div>{{ctrl.desc}}</div>
<input type='button' ng-click='ctrl.getDesc();' value='Get name' />
</div>
take a look at the guide instead :
https://docs.angularjs.org/guide/controller
works:
http://jsfiddle.net/pYh89/
you didnt load angular correctly and add several syntax errors.
var app = angular.module("main", []);
app.controller("con", function () {
this.name = 'foo';
this.getName = function () {
alert("foo");
};
});
Angular JS is missing in your code please include it after downloading it.
<script src="angular.js"></script>
You can also use online version.
You forgot different things:
Here's a corrected JSfiddle:
http://jsfiddle.net/89wfv/2/
You have to:
Use $scope instead of this to reference to the data that is to be bound to the view, eg:
app.controller("con", function($scope) {
$scope.name = 'vasu';
$scope.getName = function() {
alert();
}
});
Put the script tag in Head
Not use the html tag, that could be overwritten by JSfiddle:
Do rather something like this:
<div ng-app="main">
<div ng-controller="con">
</div>
</div>

Categories

Resources