Controller Not A Function When Placing HTML into ng-view - javascript

I've split my HTML off into a view using angular, but when I've done so I get the error:
Argument 'EventController' is not a function
This worked previously with no issue, it's only since I've tried splitting them off and writing a route and I'm really struggling to see what the problem is? I've checked all the spelling of the files, script declarations etc and that all seems fine.
My base index page is:
<html lang="en" ng-app="eventsApp">
<head>
<meta charset="utf-8" />
<title>Create Event</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css/app.css"/>
</head>
<body>
<div class="container">
<div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li>Events List</li>
<li>Create Event</li>
</ul>
</div>
</div>
<ng-view></ng-view>
</div>
<script src="lib/jquery.min.js"></script>
<script src="lib/underscore-1.4.4.min.js"></script>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="lib/angular/angular-route.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/EventController.js"></script>
<script src="js/controllers/EditEventController.js"></script>
<script src="js/controllers/EventList.js"></script>
<script src="js/services/EventData.js"></script>
<script src="js/filters.js"></script>
</body>
</html>
The HTML I'm putting in the view is:
<div style="padding-left:20px; padding-right:20px;">
<img ng-src="{{event.imageUrl}}" alt="{{event.name}}" />
<button type="button" class="btn btn-primary" ng-click="scrollToSession()">Scroll to Session</button>
<div class="row">
<div class="spann1">
<!--Style and Bind Template Directives w/ Uppercase Filter-->
<h2 ng-style="mystyle" ng-bind-template="{{event.name | uppercase}}"></h2>
</div>
</div>
<!--Disabled Directive-->
<button class="btn" ng-disabled="buttonDisabled">Disabled</button>
<!--Non-Bindable Directive-->
<div ng-non-bindable="nonBindable">{{1 + 2}}</div>
<!--Hide/Show & Class Directive-->
<h2 ng-show="boolValue">Show This</h2>
<h2 ng-hide="boolValue" ng-class="myclass">Hide This</h2>
<div class="row">
<div class="span3">
<!--Date Filter-->
<div><strong>Date:</strong> {{event.date | date:'mediumDate'}}</div>
<div><strong>Time:</strong> {{event.time}}</div>
<!--Currency Filter-->
<div><strong>Price:</strong> {{event.price | currency:'£'}}</div>
</div>
<div class="span4">
<address>
<strong>Address:</strong><br />
{{event.location.address}}<br />
{{event.location.city}}, {{event.location.province}}
</address>
</div>
</div>
<!--Expressions-->
{{[1,2,3][2]}}
<!--Number Filter-->
<div>{{3 | number:2}}</div>
<!--JSON Filter-->
<div>{{ { a:3, b:'hi', c:{aa:35} } | json }}</div>
<!--Repeat Directive-->
<hr />
<h3>Sessions</h3>
<div>
Order By:
<select ng-model="sortOrder" class="input-small">
<option value="name">Name Asc</option>
<option value="-name">Name Desc</option>
<option value="creatorName">Creator Asc</option>
<option value="-creatorName">Creator Desc</option>
<option value="level">Level Asc</option>
<option value="-level">Level Desc</option>
</select>
Show:
<select ng-model="difficulty.level" class="input-small">
<option value="">All</option>
<option value="Advanced">Advanced</option>
<option value="Introductory">Introductory</option>
<option value="Intermediate">Intermediate</option>
</select>
</div>
<ul class="thumbnails">
<li ng-repeat="session in event.sessions | orderBy:sortOrder | limitTo:3 | filter:difficulty" id={{session.id}}>
<div class="row session">
<div class="span0 well votingWidget">
<div ng-click="upVoteSession(session)" class="votingButton">
<i class="icon-chevron-up icon-white"></i>
</div>
<div class="badge badge-inverse">
<div>{{session.upVoteCount}}</div>
</div>
<div ng-click="downVoteSession(session)" class="votingButton">
<i class="icon-chevron-down icon-white"></i>
</div>
</div>
<div class="well span9">
<h4 class="well-title">{{session.name}}</h4>
<h6 style="margin-top:-10px;">{{session.creatorName}}</h6>
<!--Custom Filter-->
<span>Duration: {{session.duration | durations}}</span><br />
<span>Level: {{session.level}}</span>
<p>{{session.abstract}}</p>
</div>
</div>
</li>
</ul>
</div>
The route data is:
var eventsApp = angular.module('eventsApp', ['ngResource', 'ngRoute'])
.config(function($routeProvider){
$routeProvider.when('/newEvent', {
templateUrl:'templates/NewEvent.html',
controller: 'EditEventController'
});
$routeProvider.when('/events', {
templateUrl: 'templates/EventList.html',
controller: 'EventListController'
});
$routeProvider.when('/events/:eventId', {
templateUrl: 'templates/EventDetails.html',
controller: 'EventController'
});
}
);
And the EventController.js file:
'use strict';
eventsApp.controller('EventController', function($scope, eventData, $anchorScroll){
$scope.snippet = '<span style="color:red;">hi there</span>';
$scope.boolValue = false;
$scope.mystyle = {color:'red'};
$scope.myclass = "blue";
$scope.buttonDisabled = false;
$scope.nonBindable = true;
$scope.sortOrder = 'name';
$scope.difficulty = "";
eventData.getEvent()
.$promise.then(
function(event) {$scope.event = event; console.log(event);}
).catch(function(response) {console.log(response);}
);
$scope.upVoteSession = function(session){
session.upVoteCount++;
}
$scope.downVoteSession = function(session){
session.upVoteCount--;
}
$scope.scrollToSession() = function() {
$anchorScroll();
}
});

Seems that "use strict" is causing function declaration to break due to syntax error and not throwing specific syntax error in console:
Remove extra ()
$scope.scrollToSession() = function() {
// ^^ shouldn't be here
$anchorScroll();
}

I guess since you don't have a reference to your module when defining a controller it won't define it as it should. So try changing your first line from:
eventsApp.controller('EventController', ...
to:
angular.module('eventsApp').controller('EventController', ...
Note that eventsApp is just a local variable in your main file.

In which file do you define eventsApp? It looks like you may be attempting to use EventController before it is loaded.

Related

Code mirror not working with angular js binding variable

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

angularJS - controller stops working when I add ngRoute

So I'm trying to add routes to my angularJS app, and I'm running intro a problem where the main controller for my app stops working if I try to add 'ngRoute' to the app. Additionally, ngRoute is not working.
My code:
app.js (angular logic)
(function() {
angular.module('fccNight', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'results.html'
})
.otherwise({ redirectTo: '/' });
}])
//controllers
.controller('mainController', ['$scope', '$http', function($scope, $http) {
$scope.searchTerm = '';
$scope.data = [];
$scope.loading = false;
$scope.goingNo = [];
$scope.getResults = function() {
if($scope.searchTerm !== '') {
$scope.loading = true;
$scope.data = [];
$http.get('/api/search?term=' + $scope.searchTerm)
.success(function(results) {
$scope.loading = false;
$scope.data = results;
for(var i = 0; i < $scope.data.length; i++) {
$scope.goingNo.push($scope.data[i].going);
}
});
}
}
$scope.addGoing = function(index) {
// check if user is authenticated
if($scope.data[index].going > $scope.goingNo[index]) {
$scope.data[index].going -= 1;
}
else {
$scope.data[index].going += 1;
}
// register in db
}
}])
})();
index.html's body:
<body ng-controller="mainController" id="mainController">
<!-- CONTENT -->
<div class="container">
<div class="row text-center">
<div class="col-xs-12 main">
<h1>Where are you going tonight?</h1>
<p>Find nearby pubs and RSVP ahead of time.</p>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-8 col-lg-offset-2">
<form>
<div class="input-group">
<input id="inputSearch" ng-model="searchTerm" type="text" class="form-control" placeholder="Where are you?" autocomplete='off'>
<span id="goBtn" class="input-group-btn">
<a ng-click="getResults()" class="btn btn-default">Go</a>
</span>
</div>
</form>
</div>
</div>
<!-- LOADING -->
<div class="row loading hidden" ng-show="loading">
<div class="col-xs-12">
<div class="loader"></div>
</div>
</div>
<div class="text-center">Controller is working if search term is displayed: {{ searchTerm }}</div>
<!-- TEMPLATE -->
<div ng-view></div>
</div>
<!-- footer -->
<footer class="row-footer">
<div class="container">
<div class="row">
<div class="col-xs-12 text-center">
<a href="https://github.com/otmeek/fcc-night">
<i class="fa fa-github"></i>
</a> |
<a href="https://www.freecodecamp.com">
<i class="fa fa-fire"></i>
</a> | built using the Yelp API
</div>
</div>
</div>
</footer>
<!-- =====================SCRIPTS===================== -->
<!-- jQuery -->
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<!-- Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-route.js"></script>
<!-- custom scripts -->
<script src="js/app.js"></script>
<script src="js/scripts.js"></script>
</body>
results.html (the template I want to load in on '/' route)
<p>Results are loading</p>
<div class="row result" ng-repeat="result in data">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-8 col-lg-offset-2 result">
<div class="row">
<!-- image -->
<div class="col-xs-3 col-sm-2">
<div class="image">
<img ng-src="{{ result.image || 'img/noimage.jpg' }}">
</div>
<div ng-click="addGoing($index)" class="going text-center">
{{ result.going || 0 }} going
</div>
</div>
<!-- text -->
<div class="col-xs-9 col-sm-10">
<h4><a ng-href="{{ result.url || '#' }}">{{ result.name }}</a>
<small>{{ 'Rating: ' + result.rating || 'No rating available' }}</small></h4>
<p>{{ result.text || 'No reviews for this establishment.' }}</p>
</div>
</div>
</div>
</div>
As I said, if I remove all the routing logic from app.js and ng-view from index.html and just add in results.html, the app is running fine, controller is loading properly and everything is ok. But upon adding 'ngRoute' to the app, the results template doesn't load and I can't access any mainController variables or logic from index.html.
If anyone knows what I'm doing wrong please let me know. Thanks!
Edit: I just noticed the cdn for angular-route.js is not working. I can't find a download link for this library in the official site and I don't have bower so I have no idea where to get this file.
There is an error for angular-route.js
https://ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-route.js
its adress is wrong. There is no version for it. Write your version insteadof X.Y.Z
suchas https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-route.js
You need to change X.Y.Z by any specific version like 1.4.8 in your index.html page for angular route.
So you should use
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
instead of
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-route.js"></script>

ng-if Directive: What's the issue here?

I'm unable to figure out the mistake that's leading to nothing displaying in my div.
HomeController.js (Controller):
app.controller('HomeController', ['$scope', function($scope) {
$scope.icons = [
...
];
$scope.works = [
{
title: 'An Artsy Title for an Artsy Image',
img: 'img/an-artsy-image.png',
orientation: 'portrait',
description: "A artsy description here."
}
];
}]);
index.html (Homepage):
<!DOCTYPE HTML>
<html ng-app="portfolio">
<head>
...
<!-- AngularJS Controller -->
<script src="js/controllers/HomeController.js" type="text/javascript"></script>
<!-- AngularJS Directive -->
<script src="js/directives/introIcon.js" type="text/javascript"></script>
<script src="js/directives/workExpo.js" type="text/javascript"></script>
...
</head>
<body ng-controller="HomeController">
<div class="container-fluid hero">
...
</div>
<div class="container-fluid work-wrapper">
<div class="container work-container">
<div ng-repeat="work in works">
<work-expo info="work"></work-expo>
</div>
</div>
</div>
</body>
</html>
workExpo.js (Directive):
app.directive("workExpo", function() {
return {
restrict: 'E',
scope: 'info',
templateUrl: 'views/directives/workExpo.html'
};
});
workExpo.html (Directive Template):
<div class="row" ng-if="info.orientation === 'landscape'">
<div class="col-lg-12">
<img ng-src="{{ info.img }}" class="img-responsive center-block" />
</div>
<div class="col-lg-12">
<h3>{{ info.title }}</h3>
<p>{{ info.description }}</p>
</div>
</div>
<div class="row" ng-if="info.orientation === 'portrait'">
<div class="col-sm-6">
<img ng-src="{{ info.img }}" class="img-responsive center-block" />
</div>
<div class="col-sm-6">
<h3>{{ info.title }}</h3>
<p>{{ info.description }}</p>
</div>
</div>
It is not clear of what is it that I'm missing in the above code which is leading to my code not displaying at all. To my knowledge there is no problem with the controller or directive in general as the other directive in my code (code not shown) is working just fine.
This is what the code becomes post-compilation as per Chrome's code inspector:
...
<div class="container-fluid work-wrapper">
<div class="container work-container">
<!-- ngRepeat: work in works -->
<div ng-repeat="work in works" class="ng-scope">
<work-expo info="work">
<!-- ngIf: info.orientation === 'landscape' -->
<!-- ngIf: info.orientation === 'portrait' -->
</work-expo>
</div>
<!-- end ngRepeat: work in works -->
</div>
</div>
...
Now clearly, it has not returned any DOM elements under <!-- ngIf: info.orientation === 'portrait' --> which should rather be the case.
Please let me know in case you need any further details. Thanks.
Your scope binding is incorrect in your directive. You need to construct an object with an info property and add 2-way binding of that to the info attribute. Yu can do this as so:
scope: {info:'=info'},
This creates an info property on the scope which evaluates the value of the info attribute, i.e. evaluates work on the parent scope.
Your full directive code therefore becomes:
app.directive("workExpo", function() {
return {
restrict: 'E',
scope: { info: '=info' },
templateUrl: 'views/directives/workExpo.html'
};
});
and everything else can stay the same.
Working JsFiddle
<!-- ngIf: info.orientation === 'landscape' -->
<!-- ngIf: info.orientation === 'portrait' -->
It shows both are not matching so nothing shows
I check your code and it looks good, do one thing to check the value, put following code any where on your page
<pre>
{{ info | json}} - {{ info.orientation | json}}
</pre>

AngularJS, only runs correctly in firefox why?

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?

AngularJS : call a Controller method with ng-click [duplicate]

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>

Categories

Resources