Why angular directives are not working when added programmatically - javascript

Can some body explain me why below directive is not getting called? Its getting called if I directly add the directive to the button. I tried it adding using $timeout but still no luck.
<html>
<head>
<title>AngularJS</title>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp',[]);
app.controller('MyCtrl',function($scope,$timeout){
document.getElementById('myBtn').setAttribute('my-directive','');
});
app.directive('myDirecitive',function(){
function linkFn (scope,element,attrs){
element.bind('click',function(){
alert('Clicked');
});
}
return {
restrict:'A',
link:linkFn
}
});
</script>
</head>
<body ng-app="MyApp", ng-controller="MyCtrl">
<button id="myBtn">Test</button>
</body>
</html>

app.directive('myDirecitive',function(){
should be
app.directive('myDirective',function(){
it's best not to query the DOM inside the controller. Don't do this
document.getElementById('myBtn').setAttribute('my-directive','');
my-directive was created as an attribute directive, so it would be best to add that directly to the element like this.
<button id="myBtn" my-directive>Test</button>
I created a plunker
https://plnkr.co/edit/pispsMzbJIxrIDyIv81N?p=preview

Related

Access AngularJS $scope variable from simple JavaScript code

This does not seems duplicate of
AngularJS access scope from outside js function, as I don't want this variable access on any click!
I have AngularJS code in my Maincontroller.js is
<div ng-controller = "Maincontroller">
$scope.name = "Hello";
</div>
In My main.HTML file, I have JavaScript code where I want this $scope.name value:
<html>
<script>
// But this seems not possible with {{ name}}
</script>
</html>
Is there any possibilities to access this $scope variable in JavaScript code?
Can you please check below code. What I did is I posted the name on the UI and with the help of id I fetched the value from the javascript code with the help of getElementById and innerHTML.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body >
<div ng-app="app" ng-controller="Maincontroller">
Angualr Scope: <h1 id="name">{{name}}</h1>
</div>
<div>
A button to call a function from simple javascript function: <button onclick="getData()">Get Data: </button>
</div>
<script src="../lib/angular.js"></script>
<script>
var getData = function(){
var name = document.getElementById('name');
console.log(name.innerHTML);
}
</script>
<script>
var app = angular.module('app', []);
app.controller('Maincontroller', function ($scope) {
$scope.name = "Hello";
});
</script>
</body>
</html>

ng-bind is working fine, Why ng-bind-html is not working

angular.module('form', []).controller('formcontroller', ['$scope',
function($scope) {
$scope.input;
$scope.hello = "<h1> Welcome</h1>";
}
]);
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<form ng-app="form" ng-controller="formcontroller">
<span ng-bind="hello"></span>
<span ng-bind-html="hello"></span>
</form>
</body>
</html>
I tried by using
It results in the output as
<h1> Welcome</h1>
I tried by replacing ng-bind-html is not woking and throws an error.
<script>
angular.module('form', []).controller('formcontroller', ['$scope', function($scope) {
$scope.hello="<h1> Welcome</h1>";
}]);
</script>
Error: $sce:unsafe Require a safe/trusted value Attempting to use an
unsafe value in a safe context.
Please explain.
If you include the angular-sanitize script, inputs are sanitized by parsing the HTML into tokens
var miAp = angular.module('miAp', ['ngSanitize']);
miAp.controller('demoController', function($scope) {
$scope.bar = "<h1> Welcome</h1>";
});
<html>
<head>
<meta charset="utf-8">
<title>ngBind</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular-sanitize.min.js" type="text/javascript"></script>
<script src="cookies.js"></script>
</head>
<body ng-app="miAp" ng-controller="demoController">
<div ng-bind-html="bar"></div>
</body>
</html>
You can install and include ngSanitize.
This should fix the error.
When you use ng-bind-html to bind html string , that html need to be marked safe to prevent prevent XSS and other security issues . This is checked by Angular's Strict Contextual Escaping (SCE) mode that enabled by default .
You can see more in this link : https://docs.angularjs.org/error/$sce/unsafe .
To resolve this problem, you can view this issue :
With ng-bind-html-unsafe removed, how do I inject HTML?
Hope this help ! Thanks
Try This
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular-sanitize.min.js" type="text/javascript"></script>
var App = angular.module('sanitize', ['ngSanitize']);
App.controller('demoController', function($scope) {
$scope.bar = "<h1> Welcome</h1>";
});
<h1 data-ng-bind="hello"></h1>

Cannot access http json service in angular js

I am new to angularjs and I want to know why it isn't working.
The code has a flaw and am not sure about the same.
Thinking from java perspective,httpController defined has nested function defined inside.
Here it is my code
index.html
<!DOCTYPE html>
<html >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-app="myapp" ng-controller="HelloController">
<h2>{{message}}</h2>
</div>
<div ng-app="httpService" ng-controller="httpController">
<div>FirstName:{{user.name}}</div>
</div>
</body>
</html>
Script.js
var app = angular.module("myapp", []);
app.controller("HelloController", function($scope) {
$scope.message = "Hello, AngularJS";
});
var httpApp=angular.module("httpService",[]);
httpApp.controller("httpController",function($scope,$http){
var onUserComplete=function(response){
$scope.user=""response.data"";
}
$http.get("https://api.github.com/users/rob").then(onUserComplete);
}
);
Only one ng-app will be automatically bootstrapped on your page. That's why if you remove the first ngApp directive, the second one will work.
var httpApp = angular.module("httpService", []);
httpApp.controller("httpController", function($scope, $http) {
var onUserComplete = function(response) {
$scope.user = response.data;
}
$http.get("https://api.github.com/users/rob").then(onUserComplete);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="httpService" ng-controller="httpController">
<div>FirstName: {{user.name}}</div>
</div>
NOTE: You have a typo in your callback, remove ""s around your response.data. Also, since you are using Angular 1.5.6, you don't need to specify dependencies/inject your $http service to make your code work.
https://plnkr.co/edit/LyWCLeBeyHPzjys3LOcr?p=preview
<body ng-app="httpService">
<div ng-controller="httpController">
<div>FirstName: {{user.key}}</div>
</div>
</body>
This link is working fine...just try it out
Do not use ng-app more than once in your program...Your code would not work

How can you selectively run ngBlur code

I have a textarea and a span. The textarea has an ngBlur which calls a function. I only want that function to run its code when the cause of the blur wasn't a click on the span. How can I do that?
http://plnkr.co/edit/ENvuujbychxYum1EMmkf?p=preview
HTML
<!DOCTYPE html>
<html ng-app='app'>
<head>
<script data-require="angular.js#1.4.7" data-semver="1.4.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller='MainController as vm'>
<textarea ng-blur='vm.selective()'></textarea>
<span>span</span>
</body>
</html>
JS
angular
.module('app', [])
.controller('MainController', MainController)
;
function MainController() {
vm.focus = true;
vm.onBlur = function() {
// HOW DO I DO THIS?
// if (spanIsClicked) {
// return;
// }
vm.focus = false;
};
}
I believe you can pass in the DOM element as an argument in angular, looking like :
vm.onBlur = function($event){}
You could then access the event by using event.target. I know this works with ng-click so I'm not totally positive if the same rules apply for ng-blur.

Load angularJs controller

I had already declared my app and controller in separate file and below is how i am loading my controller html DOM but it is not showing that message. Can someone please guide how to achieve this.
HTML:
<div id="bnProblemList">
<div ng-controller="problemListCtrl" data-ng-init="init()">
<div ng-view="">this is my message = {{message}}</div>
</div>
</div>
JS:
html = $j('#bnProblemList').html();
$compile(html)(scope);
Please let me know how to inject or load ng-controller html dynamically.
Your controller declaration is wrong. You should do it like this:
var myApp = angular.module('myApp',[]);
myApp.controller('problemListCtrl', ['$scope',
function($scope) {
$scope.message = "This is my message :-)";
}
]);
A proper way is to declare your Controller into an anonymous function, and add it to a module. Then, you have to set your ngApp.
Controller.js
Here, we will declare our controller, and create an app module. Then, we will declare ctrl as our controller into our app module.
(function(){
function Controller($scope) {
$scope.name = 'toto';
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
HTML
<body ng-app='app' ng-controller="ctrl">
<p>My name is {{name}}</p>
</body>
And don't forget to include your script tag :
<script src="controller.js"></script>
You can try Like below Example:-
Html Page:
<!DOCTYPE html>
<html ng-app="MyApp">
<head>
<title> Controller</title>
<script src="../Js/angular.min.js"></script>
<script src="../Js/Controller.js"></script>
</head>
<body>
<div ng-controller="MyFirstController">
{{ Msg }}
</div>
</body>
</html>
ControllerJs Page:
var MyApp=angular.module("MyApp",[]);
MyApp.controller("MyFirstController",function($scope){
$scope.Msg="Hello First Conroller";
})
i was able to load/ inject controller dynamically by the help of below code
<div id="bn" ng-controller="myCtrl as vm">
<div ui-view=''></div>
</div>
<script>
angular.element(document).injector().invoke(function($compile, $state) {
$state.go('myCtrl');
var scope = angular.element($j("#bn")).scope();
$compile($j("#bn"))(scope);
});
</script>

Categories

Resources