Howto access the passed variable in a custom directive with JavaScript? - angularjs

I have made a custom directive and can access the passed variable in the direct.template within double squiqqly brackets like this directive.template = '<input/>{{text.incorrectAnswers}}' but how do I access it in JavaScript so I can change it and then pass it back into my directive.template?
<html ng-app="mainApp">
<head>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body ng-controller="mainController" style="padding: 20px 0">
<div class="col-xs-8">
<div class="panel panel-default">
<div class="panel-heading">Company Info</div>
<div class="panel-body">
<div ng-repeat="text in texts">
<div data-show-phrase data-text="text"></div>
</div>
</div>
</div>
</div>
<script>
var mainApp = angular.module('mainApp', []);
mainApp.controller('mainController', function ($scope) {
$scope.texts = [
{
body: 'Customer 1 is from [##blank] and Customer 2 is from [##blank].',
correctAnswers: 'Berlin;Hamburg',
incorrectAnswers: 'Stuttgart;Munich;Frankfurt'
},
{
body: 'Company 3 is located in [##blank].',
answers: 'Bremen',
incorrectAnswers: 'Hannover;Dresden;Stuttgart'
}
];
});
mainApp.directive('showPhrase', function () {
var directive = {};
directive.restrict = 'A';
directive.scope = {
text: '=text'
};
//var parts = incorrectAnswers.split(';'); //Error: incorrectAnswers is not defined
//var parts = $scope.incorrectAnswers.split(';'); //Error: incorrectAnswers is not defined
var parts = directive.incorrectAnswers.split(';'); //Error: incorrectAnswers is not defined
directive.template = '<input/>{{text.body}}';
return directive;
});
</script>
</body>
</html>

2-way bound properties available as a part of the scope object and that cannot be accessed during the creation of a directive, because no scope exists yet. You need to at least wait till linking phase or in the controller to access the scope and its properties. If you are using controllerAs syntax (with 1.3.x) then you would turn on bindToController:true to be able to access it as properties of the controller instance. And as long as you use bindings in your template, angular will take care of updating the template for dynamic changes in the bound properties.
Example:-
mainApp.directive('showPhrase', function() {
var directive = {};
directive.restrict = 'A';
directive.scope = {
text: '='
};
/*Linking function*/
directive.link = function(scope, elm) {
scope.parts = scope.text.incorrectAnswers.split(';');
console.log(parts)
}
directive.template = '<div><input/>{{text.body}} <ul><li ng-repeat="part in parts">{{part}}</li></ul></div>';
return directive;
});
var mainApp = angular.module('mainApp', []);
mainApp.controller('mainController', function($scope) {
$scope.texts = [{
body: 'Customer 1 is from [##blank] and Customer 2 is from [##blank].',
correctAnswers: 'Berlin;Hamburg',
incorrectAnswers: 'Stuttgart;Munich;Frankfurt'
}, {
body: 'Company 3 is located in [##blank].',
answers: 'Bremen',
incorrectAnswers: 'Hannover;Dresden;Stuttgart'
}];
});
mainApp.directive('showPhrase', function() {
var directive = {};
directive.restrict = 'A';
directive.scope = {
text: '='
};
directive.link = function(scope, elm) {
scope.parts = scope.text.incorrectAnswers.split(';');
console.log(parts)
}
directive.template = '<div><input/>{{text.body}} <ul><li ng-repeat="part in parts">{{part}}</li></ul></div>';
return directive;
});
<html ng-app="mainApp">
<head>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body ng-controller="mainController" style="padding: 20px 0">
<div class="col-xs-8">
<div class="panel panel-default">
<div class="panel-heading">Company Info</div>
<div class="panel-body">
<div ng-repeat="text in texts">
<div data-show-phrase data-text="text"></div>
</div>
</div>
</div>
</div>
<script>
</script>
</body>
</html>

Related

Data sharing between controllers in angular js

Hi I am new to Angularjs. I am learning how to share data between two controllers using dataservice. Looking at the tutorial I made my own program but it is not working. Can anyone suggest what I am doing wrong here?
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Services</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script>
</head>
<body>
<div ng-app="dataServiceApp">
<div ng-controller="ChildCtrl">
<h2>First controller</h2>
<button>+</button>{{Holder.value}}
</div>
<div ng-controller="ChildCtrl2">
<h2>Second controller</h2>
<button>+</button>{{Holder.value}}
</div>
</div>
<script>
var myapp = angular.module("dataServiceApp",[]);
myapp.factory('Holder', function() {
return {
value: 0
};
});
myapp.controller('ChildCtrl', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
};
});
myapp.controller('ChildCtrl2', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
};
});
</script>
</body>
</html>
You have forgotten to register onclick listeners to the buttons:
<button ng-click="increment()">+</button>{{Holder.value}}
Hope this helps. Complete working example below:
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Services</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script>
</head>
<body>
<div ng-app="dataServiceApp">
<div ng-controller="ChildCtrl">
<h2>First controller</h2>
<button ng-click="increment()">+</button>{{Holder.value}}
</div>
<div ng-controller="ChildCtrl2">
<h2>Second controller</h2>
<button ng-click="increment()">+</button>{{Holder.value}}
</div>
</div>
<script>
var myapp = angular.module("dataServiceApp",[]);
myapp.factory('Holder', function() {
return {
value: 0
};
});
myapp.controller('ChildCtrl', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
};
});
myapp.controller('ChildCtrl2', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
};
});
</script>
</body>
</html>
p.s. I also fully agree with JB Nizet's comment: check whether you really need to learn AngularJS instead of Angular 2-7/VueJS/React.

NG-Click not Loading Image AngularJS

I have a simple model with a list of names and corresponding images. I'm trying to click on the name of the image and load the corresponding image. I can't get the image to load. The list of names appears on the page, but when I click them nothing happens. Please help with code. Thx!
<!DOCTYPE html>
<html ng-app = "myApp">
<head>
<meta charset="UTF-8">
<title>Cat Clicker</title>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<link rel ="stylesheet" type "text/css" href ="clicker.css">
<script type = "text/javascript" src="Libs/angular.js"></script>
<script type = "text/javascript" src="js/CatClickerMe.js"></script>
<body>
<div ng-controller = "MainController">
<div ng-repeat = "cat in options.catList">
<h3 ng-click = "MainController.selectCat($index)">{{cat.name}}</h3>
<h3>{{MainController.selectedCat.name}}</h3>
<img ng-src = "{{MainController.selectedCat.images}}" >
</div>
</div>
</div>
</body>
</html>
JS
(function() {
"use strict";
angular.module('myApp',[]);
angular.module('myApp').controller('MainController', function($scope) {
var vm = this;
$scope.options = {
catList:[
{
name: 'Fluffy',
images: 'images/Fluffy.jpeg'
},
{
name: 'Tabby',
images: 'images/tabby.jpeg'
}
],
};
vm.selectCat=function(pos) {
vm.selectedCat = angular.copy(vm.catList[pos]);
vm.selectedCat.pos = pos;
};
activate();
function activate() {
}
})
})();
You are mixing up $ scope and vm, go with one approach. You need to use controller as syntax in the template,
<div ng-controller = "MainController as vm">
DEMO
(function() {
"use strict";
angular.module('myApp',[]);
angular.module('myApp').controller('MainController', function($scope) {
var vm = this;
vm.selectCat = selectCat;
this.options = {
catList:[
{
name: 'Fluffy',
images: 'images/Fluffy.jpeg'
},
{
name: 'Tabby',
images: 'images/tabby.jpeg'
}
],
};
function selectCat(pos) {
vm.selectedCat = pos;
};
})
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app = "myApp">
<head>
<meta charset="UTF-8">
<title>Cat Clicker</title>
<body>
<div ng-controller = "MainController as vm">
<div ng-repeat = "cat in vm.options.catList">
<h3 ng-click = "vm.selectCat(cat)">{{cat.name}}</h3>
<h3>{{vm.selectedCat.name}}</h3>
<img ng-src = "{{vm.selectedCat.images}}" >
</div>
</div>
</div>
</body>
</html>

Get autocompleted value from input in controller

I have the following in my view:
<label for="txtFrom">Pickup Location</label>
<input type="text" id="pickup" placeholder="Address, aiport, train station, hotel..." ng-model="pickup">
<label for="txtDestination">Destination</label>
<input type="text" id="destination" placeholder="Address, aiport, train station, hotel..." ng-model="destination">
<input class="btn btn-success" name="calcPrice" id="calcPrice" type="submit" value="Calculate Price" ng-click="calcPrice()">
I am using google maps api for places to autocomplete the input boxes, so if a user starts typing "Lo", he will get a list of places that starts with "Lo" and for example he chooses London.
The problem is in my controller I am not getting the whole autocompleted value. I am only getting what the user initially entered, in this case "Lo".
Here is my controller:
app.controller('BookingsCtrl', function($scope, BookingsService) {
$scope.pickup = "";
$scope.destination = "";
$scope.syncNotification = "";
$scope.calcPrice = function() {
console.log($scope.pickup);
BookingsService.save({
pickup: $scope.pickup,
destination: $scope.destination
}, function(response) {
console.log(response.message);
});
};
});
EDIT:
Here is also a snippet of the JS:
var pickup = document.getElementById('pickup');
var options = {
componentRestrictions: {
country: 'ee'
}
};
var autocompletePickup = new google.maps.places.Autocomplete(pickup, options);
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
pickup.innerHtml = place.formatted_address;
var lat = place.geometry.location.lat();
var long = place.geometry.location.lng();
});
EDIT 2 : Added service
app.service('BookingsService', function ($resource) {
return $resource('http://localhost:3000/', {});
});
EDIT 3 : Template
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="components/bootstrap/dist/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="assets/css/style.css" type="text/css" />
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDt1Y30OssBToIzSCOr3g5IkN3c0D75XVE&libraries=places"
></script>
</head>
<body ng-app='strelsau_client'>
<div class="site-wrapper">
<div class="site-wrapper-inner">
<div class="cover-container">
<div class="masthead clearfix">
<div class="inner">
<img class="masthead-brand" src="../assets/img/logo.png">
<nav>
<ul class="nav masthead-nav">
<li class="active">Home</li>
<li>Contact</li>
</ul>
</nav>
</div>
</div>
<div ng-view>
</div>
</div>
</div>
</div>
<script src="components/jquery/dist/jquery.min.js"></script>
<script src="components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="components/angular/angular.min.js"></script>
<script src="components/angular-route/angular-route.min.js"></script>
<script src="components/angular-resource/angular-resource.min.js"></script>
<script src="js/main.js"></script>
<script src="js/controllers/bookings_controllers.js"></script>
<script src="js/services/bookings_service.js"></script>
</body>
</html>
In fact pickup input element is not getting updated once the place is resolved.
The problem with this function:
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
pickup.innerHtml = place.formatted_address; //invalid
//...
});
For setting input field value should be used value property.
Anyway, given the example, try to replace it with:
(function (scope) {
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
scope.pickup = place.formatted_address;
});
})($scope);
Example
angular.module('myApp', [])
.controller('BookingsCtrl', function ($scope) {
$scope.pickup = "";
$scope.destination = "";
$scope.syncNotification = "";
var pickup = document.getElementById('pickup');
var options = {
componentRestrictions: {
country: 'ee'
}
};
var autocompletePickup = new google.maps.places.Autocomplete(pickup, options);
(function (scope) {
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
scope.pickup = place.formatted_address;
});
})($scope);
$scope.calcPrice = function () {
console.log($scope.pickup);
alert($scope.pickup);
/*BookingsService.save({
pickup: $scope.pickup,
destination: $scope.destination
}, function (response) {
console.log(response.message);
});*/
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div ng-app="myApp" ng-controller="BookingsCtrl" ng-cloak>
<label for="txtFrom">Pickup Location</label>
<input type="text" id="pickup" placeholder="Address, aiport, train station, hotel..." ng-model="pickup">
<label for="txtDestination">Destination</label>
<input type="text" id="destination" placeholder="Address, aiport, train station, hotel..." ng-model="destination">
<input class="btn btn-success" name="calcPrice" id="calcPrice" type="submit" value="Calculate Price" ng-click="calcPrice()">
</div>

ng-repeat gets commented in the browser

I have a ng-repeat on a div which shows value from an array in the controller. The div is commented when I do the inspect element in the browser. I have an outer div with the ng-controller on it.
This is the html file:
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<title></title>
<script type="text/javascript" src="../js/angular.js"></script>
<script type="text/javascript" src="../js/angular-route.js"></script>
<script type="text/javascript" src="../js/controller.js"></script>
<!-- <base href="localhost:5000/"/> -->
<base href="/"/>
</head>
<body>
<div ng-controller="firstController">
First name:<input type="text" ng-model="firstName"><br>
Last name:<input type="" ng-model="lastName"><br>
<input type="button" ng-click="loadView()" value="submit" name="">
<p>{{firstName}}</p>
<div ng-repeat="data in array">
{{data.name}}
</div>
</div>
</body>
</html>
This is the controller:
var app = angular.module('myapp',['ngRoute']);
// var app = angular.module('myapp',[]);
app.config(function($routeProvider,$locationProvider){
$routeProvider.when('/index',{
templateUrl:'./view/index.html',
controller:'firstController'
})
.when('/second/:firstName/:lastName',{
templateUrl:'./view/second.html',
controller:'secondController'
})
.otherwise({redirectTo:'/index'})
$locationProvider.html5Mode(true);
})
app.controller('firstController',function($scope,$location){
$scope.firstName = "";
$scope.lastName="";
$scope.loadView = function(){
$location.path('/second/'+$scope.firstName+"/"+$scope.lastName);
}
var arrays = [
{name:ab}, {name:ba}, {name:ac}, {name:ca}
];
$scope.array = arrays;
})
.controller('secondController',function($scope,$routeParams){
$scope.firstName = $routeParams.firstName;
$scope.lastName = $routeParams.lastName;
})
And also, when I try to navigate to second.html on button click which calls the loadView() in the controller, I see the url in the address bar has changed but it still shows the content of the first html(index.html).
The values for the array should be in single quotes unless they are variables. So instead of {name:ab} just do {name:'ab'}
Check out the snippet
var app = angular.module('myapp', []);
// var app = angular.module('myapp',[]);
app.controller('firstController', function($scope, $location) {
$scope.firstName = "";
$scope.lastName = "";
$scope.loadView = function() {
$location.path('/second/' + $scope.firstName + "/" + $scope.lastName);
}
var arrays = [{
name: 'ab'
}, {
name: 'ba'
}, {
name: 'ac'
}, {
name: 'ca'
}];
$scope.array = arrays;
})
.controller('secondController', function($scope, $routeParams) {
$scope.firstName = $routeParams.firstName;
$scope.lastName = $routeParams.lastName;
})
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-controller="firstController">
First name:
<input type="text" ng-model="firstName">
<br>Last name:
<input type="" ng-model="lastName">
<br>
<input type="button" ng-click="loadView()" value="submit" name="">
<p>{{firstName}}</p>
<div ng-repeat="data in array">
{{data.name}}
</div>
</div>
</body>
</html>
The div gets commented when the object is empty.
Make sure that your $scope.object has the data that you want.

How to set up widget with Click to show Master/Slave Checkboxes in AngularJS

I'm attempting to write a prototype for a widget that contains 2 sides. On the left side is a list of interest groups, on the right side are the associated interest topics. (i.e. Pets on the left, Birds, Dogs, Cats, on the right). The data is populated by an AJAX call to an endpoint that's making a call to the Twitter API.
I'm not sure I'm approaching this correctly and would like some advice on how to get this set up the "Angular way". I was planning on using a similar approach to this JSFiddle for having the master/slave checkboxes setup. Below is my current code.
index.html
<!doctype html>
<html ng-app="interests">
<head>
<meta http-equiv="Content-type" content="text/html" charset="utf-8">
<title>Twitter Interests</title>
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="bower_components/fontawesome/css/font-awesome.min.css">
<link rel="stylesheet" content="text/css" href="stylesheets/style.css">
</head>
<body ng-controller="InterestController as interestCtrl">
<div class="container">
<div class="row">
<div class="col-xs-12">
<label>Interests</label>
<input type="text" ng-model="search.$">
</div>
<div class="col-xs-6">
<ul id="groups">
<li group-listing group="{{ group }}" ng-repeat="group in (groups | filter: search) track by $index">
</li>
</ul>
</div>
<div class="col-xs-6">
<div topic-listing topic="{{ topic }}" ng-repeat="topic in topics track by $index">
</div>
</div>
</div>
</div>
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-route/angular-route.min.js"></script>
<script src="bower_components/underscore/underscore.js"></script>
<script src="javascripts/main.js"></script>
</body>
</html>
groupListing.html
<div ng-click="showTopics(group)">{{ group }}</div>
interestListing.html
<input type="checkbox" ng-model="topic.isChecked">{{ topic }}
main.js
var app = angular.module('interests', ['ngRoute']);
app.service('InterestService', ['$http', function ($http) {
var getInterests = function (query) {
return $http({
method: 'GET',
url: '/api/interests?=' + query
});
};
return {
getInterests: getInterests
}
}]);
app.controller('InterestController', ['$scope', 'InterestService', function ($scope, InterestService) {
var results = [];
var interests = {};
var resultArray;
var group;
var topic;
$scope.topics = [];
$scope.showTopics = function (group) {
$scope.topics = interests[group];
};
InterestService.getInterests().then(function (result) {
results = result.data.data;
_.each(results, function (result) {
resultArray = result.name.split('/');
group = resultArray[0];
topic = {};
topic.name = resultArray[1];
topic.isChecked = false;
if (_.has(interests, group)) {
interests[group].push(topic);
} else {
interests[group] = [];
interests[group].push({ name: 'All of ' + group, isChecked: false });
interests[group].push(topic);
}
});
$scope.groups = _.keys(interests);
});
}]);
app.directive('groupListing', function () {
return {
restrict: 'EA',
scope: {
group: "#"
},
controller: 'InterestController',
templateUrl: 'templates/groupListing.html'
}
});
app.directive('interestListing', function() {
return {
restrict: 'EA',
scope: {
topic: "#"
},
controller: 'InterestController',
templateUrl: 'templates/interestListing.html',
}
});

Resources