I'm using angularjs. The example I have done works perfectly in firefox, but does not work any other browser.
The error that appears in other browsers when I press add picture botton in index is:
XMLHttpRequest cannot load file:///C:/...../gifwallet/add_gif.html. Cross origin requests are only supported for HTTP.
I do not understand is what is wrong.
index.html
<html lang="es" ng-app="gifwalletApp">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="stylesheets/app.css">
<script src="javascripts/angular.js"></script>
<script src="javascripts/angular-translate.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="src/app.js"></script>
<script src="javascripts/ui-bootstrap-tpls-0.11.0.min.js"></script>
<title>GIF Wallet</title>
</head>
<body>
<div class="container">
<div ng-controller="TranslateController">
<button ng-click="changeLanguage('es')" translate="BUTTON_TEXT_ES"></button>
<button ng-click="changeLanguage('en')" translate="BUTTON_TEXT_EN"></button>
</div>
<header ng-controller="MenuController">
<ul class="nav nav-pills pull-right">
<li class="active">
<a href="#">
<span class="glyphicon glyphicon-home"></span>
<span class="badge pull-right">42</span>
</a>
</li>
<li>
<span class="glyphicon glyphicon-plus"></span>
</li>
<li>
<span class="glyphicon glyphicon-search"></span>
</li>
</ul>
<h3 class="text-muted">GIF Wallet</h3>
</header>
<div id="images" class="row" ng-controller="gifListController">
<div class="col-lg-12 media" ng-repeat="gif in giflist">
<a href="" class="pull-left thumbnail">
<img class="media-object" src="{{ gif.url }}">
</a>
<div class="media-object">
<h4 class="media-heading">{{ gif.name }}</h4>
<p>
<a><span class="glyphicon glyphicon-minus"></span> {{ 'FAVORITO' | translate }}</a>
</p>
<p>
<a><span class="glyphicon glyphicon-heart"></span> {{ 'ELIMINAR' | translate }}</a>
</p>
<p>
Link: {{ gif.url }}
</p>
</div>
</div>
</div>
<footer>
<p>© GIFWallet 2014</p>
</footer>
</div>
app.js
var gifwalletApp = angular.module('gifwalletApp', ['ui.bootstrap','pascalprecht.translate']);
gifwalletApp.config(function($translateProvider) {
$translateProvider.translations('en', {
FAVORITO: 'Favorite',
ELIMINAR: 'Delete'
})
.translations('es', {
FAVORITO: 'Favorito',
ELIMINAR: 'Eliminar'
});
$translateProvider.determinePreferredLanguage();
});
gifwalletApp.controller('TranslateController', function($translate, $scope) {
$scope.changeLanguage = function (langKey) {
$translate.use(langKey);
};
});
gifwalletApp.controller('gifListController', ['$rootScope','$scope','Storage','$http',
function($rootScope,$scope,Storage,$http){
$scope.giflist = Storage.list();
$rootScope.$on('reloadList', function(event, data){
$scope.giflist = Storage.list();
});
}]);
gifwalletApp.controller('MenuController', ['$rootScope','$scope', 'Storage','$modal',
function($rootScope,$scope, Storage, $modal) {
$scope.add = function() {
$modal.open({
templateUrl: 'add_gif.html',
controller: function($scope, $modalInstance) {
$scope.Gif = {};
$scope.save = function() {
var image = {
'name': $scope.Gif.name,
'url': $scope.Gif.url,
'tags': [],
'favorite': false
};
Storage.save(image);
$rootScope.$broadcast('reloadList');
$modalInstance.dismiss('cancel');
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
}
});
};
}
]);
gifwalletApp.service('Storage', ['$window', function($window) {
var images = [];
if (!$window.localStorage) {
alert('No tienes localStorage activado');
} else {
images = $window.localStorage.getItem('gifWallet');
}
this.save = function(image) {
if (images == null) {
images = [];
}
else {
images = angular.fromJson(images);
}
images.push(image);
imagesString = JSON.stringify(images);
$window.localStorage.setItem('gifWallet', imagesString);
}
this.get = function(key) {
}
this.remove = function(key) {
}
this.list = function() {
return angular.fromJson($window.localStorage.getItem('gifWallet'));
}
}]);
add_gif.html
<div class="modal-header">
<h3 class="modal-title">Agregar GIF</h3>
<p class="text-muted">Añade un gif favorito a tu wallet usando el nombre y la URL</p>
</div>
<div class="modal-body">
<form action="" role="form">
<div class="form-group">
<label for="name">Nombre</label>
<input type="text" id="name" ng-model="Gif.name" placeholder="Corgi bailarín" class="form-control">
</div>
<div class="form-group">
<label for="url">URL</label>
<input type="url" id="url" ng-model="Gif.url" placeholder="http://..." class="form-control">
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-link" ng-click="cancel()">Cancelar</button>
<button class="btn btn-primary" ng-click="save()">Agregar GIF</button>
</div>
You shouldn't be using the src attribute with Angular Expressions.
Use ngSrc - as described in the docs.
<img class="media-object" ng-src="{{ gif.url }}">
Edit:
In your modalpanel you'll need to make sure the form that is beeing submitted is valid
Moved here from comment:
The reason why it won't work without the http:// is probably because the input field for the URL is of type="url" and urls are not valid with http/https. So it actually is a different problem here. The form should be validated before adding an image. :)
When you call partials in Angular, it makes a cross domain request. Firefox allows it, Chrome and others don't.
So, you have to launch a local web server to make it run on all browsers (Apache, with Xampp / Mamp, whatever).
Your script only runs on firefox because firefox allow cross origin requests (AJAX requests)
and chrome will not allow cross origin request because of security policies.
So in order to run your script in chrome You have to disable web security in chrome
To disable web-securities in chrome:
kill the chrome process
press "ctrl+R" to open run menu
type "chrome --disable-web-security" without quotes and press enter
then you will be able to run your script
Please let me know If you have any issues with other browsers?
Related
Html:
<body ng-app ng-controller="OrderFormController">
<!--<h1 class="errorHeader">List of Classes</h1>-->
<header>
<div class="container">
<div id="branding">
<h1>Apex <span class="highlight"> Editor </span> </h1>
</div>
</div>
</header>
<div class="col-md-12 col-lg-12">
<div class="panel with-nav-tabs panel-default">
<div class="panel-heading">
<ul class="nav nav-tabs">
<li class="active">Apex Editor</li>
</ul>
</div>
<div class="panel-body">
<div>
<input type="text" name="apexClass" id="autocomplete" placeholder="Type the name of the Apex class you want to edit"/>
</div>
<div class="btn-group-vertical" style="padding: 1%">
<button type="button" class="btn btn-primary" id="editBtn">Edit</button>
</button>
</div>
<div class="tab-content" align="left">
<div id='error' style='display:none'>{{apexClassWrapperError.message}}</div>
<div>{{apexClassWrapper.name}}</div>
<img src="../img/ajax-loader.gif" id="loaderImage" style='display:none'>
<form>
<textarea ng-model="apexClassWrapper.body" id="code" name="code" readonly="true" >{{apexClassWrapper.body}}</textarea>
</form>
</div>
<button type="button" class="btn btn-primary" id="saveBtn" ng-click="postdata(apexClassWrapper)">Save</button>
</div>
</div>
</div>
<script src="../js/makeEditable.js"></script>
<script>
$(function() {
var editor = CodeMirror.fromTextArea(document.getElementById("code"),{
linenumber : true,
matchBrackes: true,
mode: "text/x-apex"
})
});
</script>
<footer>
<p>Web based Apex Editor</p>
<p>Developed By - Nagendra Kumar Singh</p>
</footer>
</body>
CSS and JS files included at top:
<script src="../js/codemirror.js"></script>
<script src="../js/apex.js"></script>
<script src="../js/matchbrackets.js"></script>
<link href="../css/codemirror.css" rel="stylesheet"/>
The controller is a simple one fetching the class through a RESTApi.
function OrderFormController($scope, $http) {
$('#autocomplete').autocomplete({
type: 'POST',
serviceUrl: 'http://localhost:8989/getSuggestion',
onSelect: function (suggestion) {
console.log('suggestion.value -> '+suggestion.value);
var data = {
apexClassName:suggestion.value
};
var config = {
params: data
};
$('#loaderImage').show();
$http.get("http://localhost:8989/getApexBody",config).then(function (response) {
$scope.apexClassWrapper = response.data;
$('#loaderImage').hide();
});
}
});
};
But I can only see {{apexClassWrapper.body}} in my text area, I dont see the real code when using CodeMirror, If I remove code mirror , I can see the class, but I cannot figure out a way to show the body with CodeMirror included.
There are no errors in console log and all the JS and CSS files are loaded perfectly. Please help.
Ok, So I think I may have figured it out. What I did is I set a timeout for the codemirror code to run as follows in the js file and removed it from the index.html.
$('#loaderImage').show();
$http.get("http://localhost:8989/getApexBody", config).then(function (response) {
$scope.apexClassWrapper = response.data;
$('#loaderImage').hide();
if(globalEditor) {
globalEditor.toTextArea();
}
setTimeout(function (test) {
var editor = CodeMirror.fromTextArea(document.getElementById('apexBody'), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-apex"
});
globalEditor = $('.CodeMirror')[0].CodeMirror;
}), 2000
});
The only issue in this answer is that, it creates multiple code editor window when I try to load different classes. How can I resolve that?
So finally got it working, defined a global variable and using the method toTextArea
I am building an angular application with multiple controllers.
Here is my index page:
<body ng-controller="BaseCtrl">
<div class="wrapper">
<header ng-show="HdrSection.ShowMenu">
<a ng-href="" class="show-list"><i class="fa fa-th-list">Option 1</i></a>
<a ng-href="" class="show-list"><i class="fa fa-th-list">Option 2</i></a>
<a ng-href="" class="show-list"><i class="fa fa-th-list">Option 3</i></a>
<a ng-href="" class="show-list"><i class="fa fa-th-list">Option 4</i></a>
</header>
<div class="container" ui-view>
</div>
</div> <!--wrapper div end-->
</body>
The pages of the application get rendered inside the div container. The first one gets loaded is the login page. I want to hide the header when login page is loaded and only show it whenever the page that is not a login page gets loaded. What's the best way to do that?
Should I hide it in the Login page controller?
Here is my login page:
<div id="login" class="main">
<div class="row">
<div class="col-md-2">
<img src="Images/Logo.gif" />
</div>
</div>
<div class="row">
<div class="col-md-10">
<form id="frmLogin">
<span class="prompt_text">Please enter your ID:</span>
<div class="input-group" style="width: 50%;">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" class="form-control" id="Username" ng-model="lc.user">
</div>
<br />
<input type="button" class="btn_main" value="Login" ng-click="Login()">
<br />
<span id="lblMsg" class="error_msg">{{lc.UserValidate}}</span>
</form>
</div><!--/.span12-->
</div><!--/.row-fluid-->
and here is a base controller for my index page:
(function () {
var app=angular.module("myApp", ["ui.router"]);
app.controller("BaseCtrl", ["$scope", BaseControllerFunc]);
function BaseControllerFunc($scope) {
//$('header').hide();
console.log($scope.HdrSection.ShowMenu);
$scope.HdrSection = { ShowMenu: false };
$scope.HdrSection.ShowMenu = false;
console.log($scope.HdrSection.ShowMenu);
}
})();
So far I tried 2 things:
using $('header').hide(); which works the first time page is opened but then I have no way to show the header again from any other child controller loaded by the page
and setting ng-show attribute of the header section to false in my base controller did not work as $scope.HdrSection.ShowMenu comes up as undefined
Can anyone help?
I load a number of different pages into the container div and each has its own controller. The only one I do not want header shown for is the login page
Try passing explicit the $scope form the controller injection as follow:
app.controller("BaseCtrl", ["$scope", BaseControllerFunc($scope)]);
function BaseControllerFunc($scope) {
...
}
})
Got it to work by changing my controller code to:
(function () {
var app=angular.module("myApp", ["ui.router"]);
app.controller("BaseCtrl", ["$scope", BaseControllerFunc]);
function BaseControllerFunc($scope) {
$scope = { ShowMenu: false };
}
})();
Now whenever the page loaded, the header is hidden and can be enabled by setting
$scope.parent = { ShowMenu: true };
from all other controllers
I'm trying to make my first AngularJS application and I've run into a problem.
I have an input:
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
A button:
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
and an expression:
{{ activeUser }}
I want the text to change to whatever was typed in the input once the button is clicked. For that I have the following controller:
app.controller('View1Ctrl', ['$scope', function($scope) {
$scope.userNameLogin = "";
$scope.activeUser = "Test";
$scope.setActiveUser = function() {
$scope.activeUser = $scope.userNameLogin;
console.log($scope.activeUser);
};
}]);
The initial value "Test" is shown just fine and according to the console the value of "activeUser" is being changed correctly as well. But the text in the view stays the same.
I have seen similar questions where a $scope.$apply() was the answer, but if I add that after the console.log I get
"Error: [$rootScope:inprog] $apply already in progress".
What am I missing here?
EDIT:
I have noticed that If I put the input, button and expression in the same HTML file it all works fine. However my Input and button are in a navbar in index.html while the expression is in view1.html
This is the body of index.html:
<body ng-app="myApp.view1">
<nav class="navbar navbar-inverse navbar-fixed-top" ng-controller="View1Ctrl as view">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#/view1">Kwetter</a>
</div>
<div class="navbar-collapse collapse" >
<ul class="nav navbar-nav">
<li>Home</li>
<li>Profile</li>
</ul>
<form class="navbar-form navbar-right">
<div class="form-group">
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="password" class="form-control">
</div>
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
</form>
</div>
</div>
</nav>
<div id="pagewrapper" class="container">
<div ng-view></div>
<div>Angular seed app: v<span app-version></span></div>
</div>
and this is my view1.html
<div ng-controller="View1Ctrl as view">
<!-- row 1: welcome -->
<div class="row">
<div class="col-md-12 pull-left">
<image ng-src="{{ view.users[0].avatar }}"/>
<!-- If I put the button and input here it will work -->
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
{{ activeUser }}
</div>
</div>
<!-- row 2: main content -->
<!-- left the rest of the content out because it would just clutter the page -->
I tried placing the ng-controller in <div id="pagewrapper" class="container"> instead of the first div of view1.html, but that made no difference.
I think u have misplaced the button or textbox or expression,
note : these should be inside the ng-controller.
please try this, it will work
<html>
<head>
<script data-require="angular.js#*" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app">
<div ng-controller="View1Ctrl">
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
{{activeUser}}
</div>
<h1>Hello Plunker!</h1>
</body>
</html>
script.js code
var app = angular.module("app",[]);
app.controller('View1Ctrl', ['$scope', function($scope) {
$scope.userNameLogin = "";
$scope.activeUser = "Test";
$scope.setActiveUser = function() {
$scope.activeUser = $scope.userNameLogin;
console.log($scope.activeUser);
};
}]);
refer http://plnkr.co/edit/ixbByBQ9nGm4XEqEFi4t?p=preview
You have the properties directly on $scope and that is breaking the binding. Instead try:
app.controller('View1Ctrl', ['$scope', function($scope) {
$scope.userInfo = {
userNameLogin: "",
activeUser:"Test"
}
$scope.setActiveUser = function() {
$scope.uesrInfo.activeUser = $scope.userInfo.userNameLogin;
console.log($scope.activeUser);
};
}]);
and in your view:
{{userInfo.activeUser}}
From Egghead.io https://egghead.io/lessons/angularjs-the-dot
Within your code I can't see anything causing the problem. I made a fiddle, that shows that your code works:
http://jsfiddle.net/xxvsn8xs/
You need to declare the ng-appand the ng-controller of course, like in the fiddle, to let the app work at all.
Also, an view update might not occur, if setting the activeUser actually occurs outside of the angular scope, which might be within an external library or whatever. It is true, that these could be achieved by calling $scope.$apply() directly, but it is nor recommended, as the digest might already be in progress. This is the case in your code, as why you get the according error message.
Instead use angulars $timeout service with a callback and 0 delay, that applies the value to $scope.activeUser. $timeout will check, if a digest cycle is in progress and if not, will start one.
$scope.setActiveUser = function() {
$timeout(function () {
$scope.activeUser = $scope.userNameLogin;
console.log($scope.activeUser);
});
};
Don't forget to define $timeout in your controllers dependencies:
app.controller('View1Ctrl', ['$scope', '$timeout', function($scope, $timeout) {
Angular watches the variable you bind to $scope, but if you replace that variable Angular is not able to detect it. That's why $apply would be a suggestion.
Another suggestion is to bind the variable to a 'model' variable:
app.controller('View1Ctrl', ['$scope', function($scope) {
$scope.userNameLogin = "";
$scope.myData = { activeUser: "Test" };
$scope.setActiveUser = function() {
// Angular will pick up the change in the myData object, and will update all variables attached to it
$scope.myData.activeUser = $scope.userNameLogin;
console.log($scope.myData.activeUser);
};
}]);
view:
{{ myData.activeUser }}
Do you execute your application in Apache ? I'd the same issue when I was using file:// And I fixed my issue by using a localhost.
I put my navbar (containing the input and button) in a partial and made a new directive for it. Instead of placing the navbar in the index.html I put it in the individual partials and now it works fine. I suspect the problem had something to do with different scopes.
navbar html:
<a class="navbar-brand" href="#/view1">
Kwetter
<image id="navbar-image" src="src/kwetter_logo.png"/>
</a>
</div>
<div class="navbar-collapse collapse" >
<ul class="nav navbar-nav">
<li>Home</li>
<li>Profile</li>
</ul>
<form class="navbar-form navbar-right">
<div class="form-group">
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="password" class="form-control">
</div>
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
</form>
</div>
</div>
the directive:
app.directive('navbar', function() {
return {
restrict: 'E',
templateUrl: 'partials/navbar.html',
controller: 'View1Ctrl as view'
}
});
Then I just added <navbar></navbar> to every view where I want a navbar.
Thanks everyone, your help pushed me in the right direction.
can you please tell me how to create list dynamically in angulat.js..Actullly I am able to make list when user press add button and fill the field .
In other words ,Please check this fiddle whenever you fill the fields it generate a row.And you can get Id when you click the row .Fiddle http://jsfiddle.net/wc4Jm/6/
Now I am trying to do this using bootstrap model .in other words on button click first I show a pop up screen then there is "add" button .on click that it generate the row.but I am getting "undefined".My I insert the model div inside the controller ? here is
http://jsbin.com/vubojoxo/4/
Why I am getting this error ?
XMLHttpRequest cannot load file:///C:/Users/asd/Desktop/angular/angularproject/dialog.html. Received an invalid response. Origin 'null' is therefore not allowed access.
I am getting this error when I used plunker..and run in my desktop ..
I make this html ?
<!doctype html>
<html ng-app="plunker">
<head>
<script src="angular.js"></script>
<script src="ui-bootstrap-tpls-0.2.0.js"></script>
<link href="bootstrap-combined.min.css" rel="stylesheet">
<script src="index.js"></script>
</head>
<body>
<div ng-controller="DialogDemoCtrl">
<a class="btn" data-toggle="modal" href="" ng-click="openPopupScreen()">Add Contend</a>
</div>
</body>
</html>
....
Dialog.html
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h1>Add Element</h1>
</div>
<div class="modal-body">
<form >
<label>Name:</label><input type="text" class="span3" ng-model="activeItem.name"></br>
<label>Content Name:</label><input type="password" class="span3" ng-model="activeItem.content"></br>
<button type="submit" class="btn btn-success" ng-click="addItem()">Add In List</button>
<button type="reset" class="btn ">Clear</button>
</form>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal" aria-hidden="true">close</a>
</div>
js code:
var myApp = angular.module('plunker', ['ui.bootstrap']);
myApp.controller('DialogDemoCtrl', function($scope,$dialog) {
$scope.items = [];
$scope.activeItem = {
id:'',
name: '',
content: ''
};
$scope.addItem = function () {
$scope.activeItem.id = $scope.items.length + 1;
$scope.items.push($scope.activeItem);
$scope.activeItem = {}; /* reset active item*/
};
$scope.getId = function (item) {
alert('ID: '+item.id);
};
$scope.openPopupScreen = function () {
alert('Check Open pop up screen');
$dialog.dialog({}).open('dialog.html');
};
});
Check this Plunker
In this example i used angular-ui library which wraps bootstrap's modal to angular
based on this StackOverflow Answer
ModalDemoCtrl
$scope.items = [];
$scope.getId = function(item) {
alert('ID: ' + item.id);
};
// This opens a Bootstrap modal
$scope.open = function() {
var modalInstance = $modal.open({
template: $scope.modal_html_template,
controller: ModalInstanceCtrl
});
modalInstance.result.then(function(newItem) {
// On modal success
newItem.id = $scope.items.length + 1;
$scope.items.push(newItem);
}, function() {
// On modal cancelation
});
}
ModalInstanceCtrl
$scope.name = '';
$scope.content = '';
$scope.ok = function() {
var response = {
'name': $scope.name,
'content': $scope.content
};
$modalInstance.close(response);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
HTML
<body>
<div ng-controller="ModalDemoCtrl">
<div inner-html-bind="" inner-html="modal_html_template" class="hidden">
<div class="modal-header">
<h3>I'm a modal!</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label>Name</label>
<!-- using $parent because ui-bootstrap nested 2 controllers. this is a workaround -->
<input type="text" class="form-control" ng-model="$parent.name" placeholder="Enter Name">
</div>
<div class="form-group">
<label>Content</label>
<!-- using $parent because ui-bootstrap nested 2 controllers. this is a workaround -->
<input type="text" class="form-control" ng-model="$parent.content" placeholder="Enter Content">
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</div>
<div class="container">
<h2>Modal Example https://stackoverflow.com/questions/24988561</h2>
<button class="btn" ng-click="open()">Open Modal</button>
<div>
<ul>
<li ng-repeat="item in items">
<a ng-click="getId(item)">{{ item.id }} | {{ item.name + ' ' + item.content }}</a>
</li>
</ul>
</div>
</div>
</div>
</body>
I have a simple loop with ng-repeat like this:
<li ng-repeat='task in tasks'>
<p> {{task.name}}
<button ng-click="removeTask({{task.id}})">remove</button>
</li>
There is a function in the controller $scope.removeTask(taskID).
As far as I know Angular will first render the view and replace interpolated {{task.id}} with a number, and then, on click event, will evaluate ng-click string.
In this case ng-click gets totally what is expected, ie: ng-click="removeTask(5)". However... it's not doing anything.
Of course I can write a code to get task.id from the $tasks array or even the DOM, but this does not seem like the Angular way.
So, how can one add dynamic content to ng-click directive inside a ng-repeat loop?
Instead of
<button ng-click="removeTask({{task.id}})">remove</button>
do this:
<button ng-click="removeTask(task.id)">remove</button>
Please see this fiddle:
http://jsfiddle.net/JSWorld/Hp4W7/34/
One thing that really hung me up, was when I inspected this html in the browser, instead of seeing it expanded to something like:
<button ng-click="removeTask(1234)">remove</button>
I saw:
<button ng-click="removeTask(task.id)">remove</button>
However, the latter works!
This is because you are in the "Angular World", when inside ng-click="" Angular all ready knows about task.id as you are inside it's model. There is no need to use Data binding, as in {{}}.
Further, if you wanted to pass the task object itself, you can like:
<button ng-click="removeTask(task)">remove</button>
Also worth noting, for people who find this in their searches, is this...
<div ng-repeat="button in buttons" class="bb-button" ng-click="goTo(button.path)">
<div class="bb-button-label">{{ button.label }}</div>
<div class="bb-button-description">{{ button.description }}</div>
</div>
Note the value of ng-click. The parameter passed to goTo() is a string from a property of the binding object (the button), but it is not wrapped in quotes. Looks like AngularJS handles that for us. I got hung up on that for a few minutes.
this works. thanks. I am injecting custom html and compile it using angular in the controller.
var tableContent= '<div>Search: <input ng-model="searchText"></div>'
+'<div class="table-heading">'
+ '<div class="table-col">Customer ID</div>'
+ ' <div class="table-col" ng-click="vm.openDialog(c.CustomerId)">{{c.CustomerId}}</div>';
$timeout(function () {
var linkingFunction = $compile(tableContent);
var elem = linkingFunction($scope);
// You can then use the DOM element like normal.
jQuery(tablePanel).append(elem);
console.log("timeout");
},100);
Above answers are excellent. You can look at the following full code example so that you could exactly know how to use
var app = angular.module('hyperCrudApp', []);
app.controller('usersCtrl', function($scope, $http) {
$http.get("https://jsonplaceholder.typicode.com/users").then(function (response) {
console.log(response.data)
$scope.users = response.data;
$scope.setKey = function (userId){
alert(userId)
if(localStorage){
localStorage.setItem("userId", userId)
} else {
alert("No support of localStorage")
return
}
}//function closed
});
});
#header{
color: green;
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<title>HyperCrud</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<!-- NAVBAR STARTS -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">HyperCrud</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
<li class="dropdown">
Apps<span class="caret"></span>
<ul class="dropdown-menu">
<li>qAlarm »</li>
<li>YtEdit »</li>
<li>GWeather »</li>
<li role="separator" class="divider"></li>
<li>WadStore »</li>
<li>chatsAll</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>Login</li>
<li>Register</li>
<li>Services<span class="sr-only">(current)</span></li>
</ul>
</div>
</div>
</nav>
<!--NAVBAR ENDS-->
<br>
<br>
<div ng-app="hyperCrudApp" ng-controller="usersCtrl" class="container">
<div class="row">
<div class="col-sm-12 col-md-12">
<center>
<h1 id="header"> Users </h1>
</center>
</div>
</div>
<div class="row" >
<!--ITERATING USERS LIST-->
<div class="col-sm-6 col-md-4" ng-repeat="user in users">
<div class="thumbnail">
<center>
<img src="https://cdn2.iconfinder.com/data/icons/users-2/512/User_1-512.png" alt="Image - {{user.name}}" class="img-responsive img-circle" style="width: 100px">
<hr>
</center>
<div class="caption">
<center>
<h3>{{user.name}}</h3>
<p>{{user.email}}</p>
<p>+91 {{user.phone}}</p>
<p>{{user.address.city}}</p>
</center>
</div>
<div class="caption">
DELETE
UPDATE
</div>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<a href="/regiser/">
<img src="http://img.bhs4.com/b7/b/b7b76402439268b532e3429b3f1d1db0b28651d5_large.jpg" alt="Register Image" class="img-responsive img-circle" style="width: 100%">
</a>
</div>
</div>
</div>
<!--ROW ENDS-->
</div>
</body>
</html>
HTML:
<div ng-repeat="scannedDevice in ScanResult">
<!--GridStarts-->
<div >
<img ng-src={{'./assets/img/PlaceHolder/Test.png'}}
<!--Pass Param-->
ng-click="connectDevice(scannedDevice.id)"
altSrc="{{'./assets/img/PlaceHolder/user_place_holder.png'}}"
onerror="this.src = $(this).attr('altSrc')">
</div>
</div>
Java Script:
//Global Variables
var ANGULAR_APP = angular.module('TestApp',[]);
ANGULAR_APP .controller('TestCtrl',['$scope', function($scope) {
//Variables
$scope.ScanResult = [];
//Pass Parameter
$scope.connectDevice = function(deviceID) {
alert("Connecting : "+deviceID );
};
}]);
Here is the ng repeat with ng click function and to append with slider
<script>
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.employees = [
{ 'id': '001', 'name': 'Alpha', 'joinDate': '05/17/2015', 'age': 37 },
{ 'id': '002', 'name': 'Bravo', 'joinDate': '03/25/2016', 'age': 27 },
{ 'id': '003', 'name': 'Charlie', 'joinDate': '09/11/2015', 'age': 29 },
{ 'id': '004', 'name': 'Delta', 'joinDate': '09/11/2015', 'age': 19 },
{ 'id': '005', 'name': 'Echo', 'joinDate': '03/09/2014', 'age': 32 }
]
//This will hide the DIV by default.
$scope.IsVisible = false;
$scope.ShowHide = function () {
//If DIV is visible it will be hidden and vice versa.
$scope.IsVisible = $scope.IsVisible ? false : true;
}
});
</script>
</head>
<body>
<div class="container" ng-app="MyApp" ng-controller="MyController">
<input type="checkbox" value="checkbox1" ng-click="ShowHide()" /> checkbox1
<div id="mixedSlider">
<div class="MS-content">
<div class="item" ng-repeat="emps in employees" ng-show = "IsVisible">
<div class="subitem">
<p>{{emps.id}}</p>
<p>{{emps.name}}</p>
<p>{{emps.age}}</p>
</div>
</div>
</div>
<div class="MS-controls">
<button class="MS-left"><i class="fa fa-angle-left" aria-hidden="true"></i></button>
<button class="MS-right"><i class="fa fa-angle-right" aria-hidden="true"></i></button>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="js/multislider.js"></script>
<script>
$('#mixedSlider').multislider({
duration: 750,
interval: false
});
</script>