How to implement custom directive in angular js? - javascript

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

Related

How to send value in JavaScript variable to a Angular js variable

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;
});
}]);

Unable to compile a dynamically added Directive into a page

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]);

Change Appended each text

I'm not getting result properly using append event instead of using ng-repeat in adding each name. Can you please help me how can I change added each name from a single input field. Tell me without using ng-repeat in this, because ng-repeat functionality is not working to me for my further running functionalities, you can solve this using jquery or javascript if it's possible without using ng-repeat. Thanks in advance..
Here is JSBin
var app = angular.module('myapp', ['ngSanitize']);
app.controller('AddCtrl', function ($scope, $compile) {
$scope.my = {name: 'untitled'};
$scope.add_Name = function (index) {
var namehtml = '<label ng-click="selectName($index)">{{my.name}} //click<br/></label>';
var name = $compile(namehtml)($scope);
angular.element(document.getElementById('add')).append(name);
};
$scope.selectName = function (index) {
$scope.showName = true;
};
});
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js"></script>
<script src="https://code.angularjs.org/1.5.0-rc.0/angular-sanitize.min.js"></script>
</head>
<body ng-controller="AddCtrl">
<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>
ng-repeat would be perfect for such cases. Not sure what makes you avoid that.
You can have a counter which will increment every time Name is added. Also pass same counter name as an argument for selectName function.
Every time selectName is called, argument value will be set as an model
Try this:
var app = angular.module('plunker', []);
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;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body ng-app="plunker" 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>
Working demo

how to bind names between text box to label

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>

What am I doing thats causing Unknown Provider when Adding both a service and a filter or multiple services

This is most likely due to my lack of experience and overlooking something fundamental but between SO, the angulajs tutorials and guide as well as Googling and I can't find an explaination or example that I can follow.
I have successfully created a factory and used it in my controller and a filter but Only one or the other. when I try to add both to the module I get Error: Unknown provider: memberFactoryProvider <- memberFactory
my code is below but some questions I have include:
1. When adding the factory and service (or multiple factories/filters) to a module is it enough to create them the same way as you with a single factory i.e.
if I have a number of factories delclared like so:
'use strict';
angular.module('testApp', [])
.factory('factory1', function () {
var obj = {};
obj.text = "This is a test";
return obj;
});
angular.module('testApp', [])
.factory('factory2', function () {
var obj = {};
obj.text = "This is another test";
return obj;
});
is it enough to inlcude the two in app.js using angular.module('testApp', ['factory1', 'factory2']);
2. I have noticed some posts online that when creating a filter/factory they append the appname e.g.:
angular.module('testApp', [])
.factory('testApp.factory1', function () {
var obj = {};
obj.text = "This is a test";
return obj;});
is this required or personal preference?
Finally below is all my code, as mentioned above, all work indiviually but when I try to combine them I get the error mentioned above, any advice or help is greatly appreciated
index.html
<!DOCTYPE html>
<html data-ng-app="testApp">
<head>
<title>prototype</title>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
</head>
<body>
<div data-ng-controller="myController">
<br/>
<div data-ng-repeat="n in [] | range:5">
<div data-ng-repeat="">{{test}}</div>
</div>
</div>
<br/>
<br/>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/services.js"></script>
<script type="text/javascript" src="js/filters.js"></script>
<script type="text/javascript" src="js/controllers.js"></script>
</body>
</html>
App.js
'use strict';
angular.module('testApp', ['memberFactory', 'range']);
services.js
'use strict';
angular.module('testApp',[])
.factory('memberFactory', function(){
var obj = {};
obj.text = "This is a test";
return obj;
});
filters.js
'use strict';
angular.module('testApp',[]).filter('testApp.range', function() {
return function(input, total) {
total = parseInt(total);
for (var i=0; i<total; i++)
input.push(i);
return input;
};
});
controllers.js
function myController($scope, memberFactory){
$scope.test= memberFactory.text;
}
First of all you should be doing this
angular.module('testApp', [])
.factory('factory1', function () {
var obj = {};
obj.text = "This is a test";
return obj;
})
.factory('factory2', function () {
var obj = {};
obj.text = "This is another test";
return obj;
});
You shouldn't create 2 modules of the same name.
And I think that this
angular.module('something', ['here', 'is', 'for modules', 'only'];
I think what you are trying to do is this.
You have 2 modules?
var helpers = angular.module('helpers', []);
Then you should do
var app = angular.module('app', ['helpers']);
Then you will have access to all factories that are attached to helpers and app
Say for example you want your filters in another file there are a few ways to do it
var filters = angular.module('filters', []);
filters.filter('name', func...);
Then you include it in your app like so
var app = angular.module('app', ['helpers', 'filters']);

Categories