I am trying to add a dynamically added element directive into a page but it is not working and getting compiled in the page it is added. Here is the plunker code. What is wrong with the code?
http://plnkr.co/edit/BFPxAvEahT1I930mvB5r
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller("fCtrl",function($scope,$compile){
$scope.xx = ['x','c','y','z','a'];
$scope.add = function(){
var templ = document.getElementById('test').innerHTML;
templ = templ+'<datan-type content="test1" con="{{xx}}"></datan-type>';
document.getElementById('test').innerHTML = templ;
//$compile(document.getElementById('test').innerHTML)($scope);
alert(document.getElementById('test').innerHTML);
}
});
app.directive('datanType', function ($compile) {
return {
restrict: 'E',
replace: true,
link: function (scope, ele, attrs) {
var testTemplate1 = '<h1 ng-repeat="x in arr">Test{{x}}</h1>';
var testTemplate2 = '<h1>Test2</h1>';
var testTemplate3 = '<h1>Test3</h1>';
var template = '';
scope.arr = eval(attrs.con);
switch(attrs.content){
case 'test1':
template = testTemplate1;
break;
case 'test2':
template = testTemplate2;
break;
case 'test3':
template = testTemplate3;
break;
}
ele.html(template);
$compile(ele.contents())(scope);
}
};
});
</script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="fCtrl">
<p>Result:</p>
<datan-type content="test1" con="{{xx}}"></datan-type>
<div id="test"></div>
<button ng-click="add()">Add Form Elem Eg - Error Area</button>
</body>
</html>
Gary, this was killing me so I made it my morning goal to figure out the silly syntax:
Working Plnkr - Clicky
Change your controller code to :
var elementToAdd = angular.element('<datan-type content="test1" con="{{xx}}"></datan-type>');
$compile(elementToAdd)($scope);
document.getElementById('test').appendChild(elementToAdd[0]);
Related
A similar question was asked in this forum post, but I am still unable to convert the code from JSfiddle to HTML.
The JSfiddle example can be found here.
I tried to use the technique suggested in the forum post previously mentioned, that is:
<html>
<head>
<style type="text/css">
// CSS Content
</style>
</head>
<body ng-app="myApp">
<!-- some html elements -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script language="JavaScript" type="text/javascript">
// more js here.
</script>
</body>
As I am a complete noob, I simply copied the HTML and Javascript into the some html elements and // more js here sections. Without changing the API key, the final code looked like this:
<html>
<head>
<style type="text/css">
// CSS Content
</style>
</head>
<body ng-app="myApp">
<div ng-app="myapp" ng-controller="WeatherCtrl">
<h2>Weather in Salzburg, Austria</h2>
<weather-icon cloudiness="{{ weather.clouds }}"></weather-icon>
<h3>Current: {{ weather.temp.current | temp:2 }}</h3>
min: {{ weather.temp.min | temp }}, max: {{ weather.temp.max | temp }}
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script language="JavaScript" type="text/javascript">
'use strict';
var myapp = angular.module('myapp', []);
myapp.factory('weatherService', function($http) {
return {
getWeather: function() {
var weather = { temp: {}, clouds: null };
$http.jsonp('http://api.openweathermap.org/data/2.5/weather?q=Salzburg,at&units=metric&callback=JSON_CALLBACK&APPID=f9dbd911bc01df1d9ce563b2ba4d3209').success(function(data) {
if (data) {
if (data.main) {
weather.temp.current = data.main.temp;
weather.temp.min = data.main.temp_min;
weather.temp.max = data.main.temp_max;
}
weather.clouds = data.clouds ? data.clouds.all : undefined;
}
});
return weather;
}
};
});
myapp.filter('temp', function($filter) {
return function(input, precision) {
if (!precision) {
precision = 1;
}
var numberFilter = $filter('number');
return numberFilter(input, precision) + '\u00B0C';
};
});
myapp.controller('WeatherCtrl', function ($scope, weatherService) {
$scope.weather = weatherService.getWeather();
});
myapp.directive('weatherIcon', function() {
return {
restrict: 'E', replace: true,
scope: {
cloudiness: '#'
},
controller: function($scope) {
$scope.imgurl = function() {
var baseUrl = 'https://ssl.gstatic.com/onebox/weather/128/';
if ($scope.cloudiness < 20) {
return baseUrl + 'sunny.png';
} else if ($scope.cloudiness < 90) {
return baseUrl + 'partly_cloudy.png';
} else {
return baseUrl + 'cloudy.png';
}
};
},
template: '<div style="float:left"><img ng-src="{{ imgurl() }}"></div>'
};
});
</script>
</body>
My output looks like this:
Could anyone please show me how to do this?
The problem is that you are declaring two apps remove "ng-app="myApp" from the body <body> tag.
I am using button to create element in javascript DOM way as follows
var app = angular.module('app', []);
function createElement2(resource){
el= document.createElement('textarea');
$(el).attr('ID', "Textbox0");
$(el).attr('type', "text");
$(el).attr('value', "Textbox0");
$(el).attr("name","Textbox0");
$(el).attr("ng-model", "html");
//this line will be diffrent for element
document.getElementById("areaT").appendChild(el)
}
app.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
console.log("test")
ele.html(html);
$compile(ele.contents())(scope);
});
}
};
});
function MyController($scope) {
$scope.click = function(arg) {
alert('Clicked ' + arg);
}
$scope.html = '<a ng-click="click(1)" href="#">Click me</a>';
}
The problem is I want to a tag customize directive Angluarjs to any element create with different validtion and the dirctive code execute only when the page load.In another words I want to execute the next piece of code every time I create element
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.0.7" data-semver="1.0.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
<h1>Compile dynamic HTML</h1>
<div id="areaT" ng-controller="MyController">
<textarea ng-model="html"></textarea>
<div dynamic="html"></div>
</div>
<input type="button" onclick="createElement2(this)">
</body>
</html>
note that the textarea in the html code when enter any code the console.log("test") and so on will be execute. what I need when click on button the textarea that will be adding execute what the textarea in the html code execute (console.log("test") and so) when enter text inside it
I am having a problem sending a value of JavaScript variable to Angular js variable. I want to send a value in dataArray variable in JavaScript to Angular js variable $scope.test
html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="angular.js"></script>
<script type='text/javascript'>
$(document).ready(function () {
// $("#fileUpload").load('test.csv');
$.get("test.csv", function(data) {
alert(data);
var rows = data.split("\r\n");
if(rows.length>0){
alert("inside if");
var firstRowCells = GetCSVCells(rows[0], ",");
var dataArray = new Array();
for(var i=1;i<rows.length;i++)
{
var cells = GetCSVCells(rows[i], ",");
var obj = {};
for(var j=0;j<cells.length;j++)
{
obj[firstRowCells[j]] = cells[j];
}
dataArray.push(obj);
}
$("#dvCSV").html('');
alert(dataArray);
$("#dvCSV").append(JSON.stringify(dataArray));
var myjson=JSON.stringify(dataArray);
//alert(myjson);
}
});
function GetCSVCells(row, separator){
return row.split(separator);
}
});
</script>
</head>
<body>
<div id="container">
Test
</div>
<div ng-app="sortApp" ng-controller="mainController">
<div id="dvCSV" ng-model="dataf" ng-bind="bdc">dfsgdfd</div>
</div>
<script src="app.js"></script>
</body>
</html>
app.js:
angular.module('sortApp', [])
.controller('mainController', function($scope) {
window.alert("Angular");
window.alert("asdfad"+$scope.bdc);
$scope.test=$scope.dataf;
window.alert($scope.myjson);
window.alert("test"+$scope.test.value);
You can do this all jquery stuff in angular using http service of angular js.
For simple http service you can refer this link -
http://www.w3schools.com/angular/angular_http.asp
I agree with previous answer. Also its wrong to use $(document).ready along with using angular framework in you application.
Try something like this:
angular.module('sortApp', [])
.service('loadTestCsv' ['$http', function($http) {
return $http.get('test.csv').then(data => {
// do all data processing you need
return data;
});
}]);
.controller('mainController', ['$scope', 'loadTestCsv', function($scope, loadTestCsv) {
loadTestCsv().then(data => {
$scope.data = data;
});
}]);
How can i bind values from shown single text box to label value ??
If i use ng-repeat in this i'm facing issues to my further functionalities.. can u pls solve this issue. i'm not able to bind between them ....Working DEMO
var app = angular.module('myapp', []);
app.controller('MainCtrl', function($scope, $compile) {
$scope.my = {name: 'untitled'};
var counter=0;
$scope.add_Name = function(index) {
var myName='untitled'+counter;
var namehtml = '<label ng-click="selectName(\''+myName+'\')">'+myName+' //click<br/></label>';
var name = $compile(namehtml)($scope);
angular.element(document.getElementById('add')).append(name);
++counter;
};
$scope.selectName = function(val) {
$scope.my.name=val;
$scope.showName = true;
};
});
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="add_Name($index)">Add Names</button>
<div id="add"></div><br/>
<form ng-show="showName">
<label>Name Change(?)</label><br/>
<input ng-model="my.name">
</form>
</body>
</html>
I have updated my code, here's a working version, finally i got the result:
var app = angular.module('myapp', []);
app.controller('MainCtrl', function($scope, $compile) {
$scope.my = {name: 'untitled'};
$scope.mies=[]; // added an array to store the generated values
var counter=0;
$scope.add_Name = function(index) {
$scope.mies[counter]={name: 'untitled'+counter}; // insert a new object into the array
var namehtml = '<label ng-click="selectName(mies[\''+counter+'\'])">{{mies['+counter+'].name}} //click<br/></label>';
var name = $compile(namehtml)($scope);
angular.element(document.getElementById('add')).append(name);
++counter;
};
$scope.selectName = function(val) {
$scope.my=val; // set my to val instead of my.name
$scope.showName = true;
};
});
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="add_Name($index)">Add Names</button>
<div id="add"></div><br/>
<form ng-show="showName">
<label>Name Change(?)</label><br/>
<input ng-model="my.name">
</form>
</body>
</html>
I tried to build a custom 'button' directive with the following code.But some where it went wrong could you please help me to sort it out.and here I am attaching code snippet to get a clear picture. Thanks in Advance.
<html>
<head>
<title>Custom Directives</title>
</head>
<body>
<h2>AngularJS</h2>
<div ng-app = "mainApp" ng-controller = "ButtonController">
<myButton name="Sai"></myButton><br/>
<myButton name="Bharat"></myButton>
</div>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.directive('myButton', function() {
var directive = {};
directive.restrict = 'E';
directive.transclude = true;
directive.template = "<button>{{myButton.name}}</button>";
directive.scope = {
myButton : "=name"
}
directive.compile = function(element, attributes) {
element.css("border", "1px solid #cccccc");
var linkFunction = function($scope, element, attributes) {
element.html("<button> $scope.myButton.name </button>");
}
return linkFunction;
}
return directive;
});
mainApp.controller('ButtonController', function($scope) {
$scope.Sai = {};
$scope.Sai.name = "Sai";
$scope.Bharat = {};
$scope.Bharat.name = "Bharat";
});
</script>
</body>
</html>
You are declaring directive in wrong way in html.
html name should be snake-case like this
<my-button name="Bharat"></my-button>
JSFIDDLE