Is there any downsite if i put directive code in controller and why i have access to it? - angularjs

I have the following code:
index.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body ng-app="myModule">
<div ng-controller="myController">
<div some-message></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
<script src="script.js"></script>
</body>
</html>
script.js file
var app = angular.module('myModule', []);
var myController = function($scope) {
$scope.message = 'sdsd';
var technologies = [
{ name: "C#", likes: 0, dislikes: 0 },
{ name: "ASP.NET", likes: 0, dislikes: 0 },
{ name: "SQL", likes: 0, dislikes: 0 },
{ name: "AngularJS", likes: 0, dislikes: 0 }
];
$scope.technologies = technologies;
$scope.updateLikes = function(tech) {
tech.likes++;
}
}
app.controller('myController', myController)
app.directive('someMessage', function() {
return {
templateUrl: 'some-message.html',
controller: function($scope) {
$scope.testName = "Andrej";
console.log('tech', $scope.technologies)
// $scope.updateLikes = function(tech) {
// tech.likes++;
// }
}
}
})
and
some.message.html
<ul>
<li ng-repeat="tech in technologies">
{{ tech.name }} -- {{ tech.likes }} <button ng-click="updateLikes(tech)">Set like</button>
</li>
</ul>
so as you can see inside my module i have one controller and directive.
I have function where on button click i am increasing the likes for every technology.
Because i am new to angular.js i don't know.
Is there downsite if my updateLikes function is in the controller , instead of directive ?
Note i have the same function in the directive and it works same.
And why the function
updateLikes can be executed in the controller ?
As i understood when we have nested scopes the child scope can access the scope in the parent but not in the opposite case

Related

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>

Unable to invoke controller function from ng-dropdown-multiselect directive

I need to bind an event in my controller to be called when there is a change in value of a dropdown. This dropdown is a multi-select dropdown -which is in a directive.
I have been able to customize the dropdown using the settings available - however, unable to bind the event.
Here is the code
HTML:
<html>
<head>
<meta charset="utf-8">
<title>AngularJS Dropdown Multiselect</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<script src="./angular.min.js"></script>
<!--<script src="./ui-bootstrap-tpls.js"></script>-->
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.7.0/lodash.min.js"></script>
<script src="./app.js"></script>
<style>
.noscroll {
overflow: hidden;
}
</style>
</head>
<body>
<div ng-app="myApp" ng-controller="AppCtrl">
<div ng-dropdown-multiselect="" options="fruitdata"
selected-model="fruitmodel" checkboxes="true"
extra-settings="fruitsettings" events="extraEvents">
</div>
Selected Model: {{fruitmodel}} | json
</div>
</body>
</html>
JS:
'use strict';
var app = angular.module('myApp', ['angularjs-dropdown-multiselect']);
app.controller('AppCtrl', function ($scope) {
$scope.fruitmodel = [];
$scope.fruitsettings = {
enableSearch: false
};
$scope.fruitdata = [{
"label": "Apple",
"id": 1
}, {
"label": "Banana",
"id": 2
}, {
"label": "Orange",
"id": 3
}, {
"label": "Pineapple",
"id": 4
}, {
"label": "Strawberry",
"id": 5
}];
$scope.example2settings = {
displayProp: 'id'
};
$scope.extraEvents = {
onItemDeselect: '$scope.onChange'
};
$scope.onChange = function() {
console.log($scope.fruitdata);
};
});
I need to detect the change to the model and take action based on this. I tried two approaches - adding ng-change to the dropdown as below - however, this does not work.
<div ng-dropdown-multiselect="" options="fruitdata"
selected-model="fruitmodel" checkboxes="true"
extra-settings="fruitsettings" ng-change="onChange()">
</div>
The directive does seem to allow extending the event handling - however, I guess I am not getting it right.
Snapshot from AngularJS Dropdown Multiselect
Seems like you have to use:
<div ng-dropdown-multiselect="" ... events="eventsCallback"></div>
and into your controller:
$scope.eventsCallback = {
onItemSelect: function () { ... },
onSelectionChanged: function () { ... }
}
Is $scope.fruitmodel where you are storing the selected items? You can use $scope.$watchCollection to act on changes.
$scope.$watchCollection('fruitmodel', function(newValue, oldValue) {
console.log(newValue, oldValue);
});

How Can I Bring SQL Data Directly into a Controller in AngularJS

As shown below, in the controller.js, I have tried to use the { name: 'item' } style and it worked in the viewer.
However, I would like to pull the data from the SQL Database.
I tried using {{member.member_name}} but it didn't work.
$http.get('../crud/members_select.php').then(function(response){
$scope.members = response.data;
});
this.items = [
{ member_name: 'Tim' },
{ member_name: 'Dave' },
{ member_name: 'Jenny' }
];
Thus, my question is "How can I do the {{member_name}} thing in order to repeat the data in a single code from SQL Database?"
Below is the HTML CODE.
<div class="ibox-content">
<select ng-options="name as member.member_name for n in members"
multiple
ng-model="selections"
bs-duallistbox></select>
</div>
Thank you in advance!!
You need to do it this way
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
<script src="https://code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="selectExample">
<script>
angular.module('selectExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.items = [
{ member_name: 'Tim' },
{ member_name: 'Dave' },
{ member_name: 'Jenny' }
];
$scope.selections = [];
}]);
</script>
<div ng-controller="ExampleController">
<label>Color (null not allowed):
<select ng-model="selections" ng-options="item.member_name for item in items" multiple></select>
</label>
<hr/>
Currently selected: {{ selections }}
</div>
</body>
</html>

get array values based on checkbox

I have a situation where there are 3 check box ("initially checked"). Since it as 3 check box it will use ng-repeat for 3 time and loops the division for there time. Now once i uncheck any of the check box it should display div for 2 time. So far ,
$scope.items = [
{id: 0, title: "apple",selected:true},
{id: 1, title: "orange",selected:true},
{id: 2, title: "grapes",selected:true},
];
On ng-click in each check box i have called a function test("apple").
$scope.test = function(vals) {
$scope.vl=[];
for(var i=0;i<$scope.items.length;i++) {
if($scope.items[i].title == vals) {
console.log("dnt push");
}
else {
$scope.vl.push({
id: $scope.items[i].id,
title: $scope.items[i].title,
selected:true
});
}
}
console.log("vl array");
console.log($scope.vl);
}
Problem I am facing is it works fine for 1st uncheck but not when i do for multiple uncheck. When i check unchecked its not loading div.
In HTML I am using like,
<div ng-repeat="item in vl"> some tags </div>
not quite sure about your question, but hope my answer can give you some hints.
plunker demo
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.items = [{
id: 0,
title: "apple",
selected: true
}, {
id: 1,
title: "orange",
selected: true
}, {
id: 2,
title: "grapes",
selected: true
}];
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<div ng-repeat="item in items">
<input type="checkbox" ng-model="item.selected">{{item.title}}
</div>
{{items | json}}
</body>
</html>
If and only if you want to put in an array the item who are checked :
http://plnkr.co/edit/DvoPBBvKf3AhYM4qcBhx?p=preview
html
<div ng-repeat="item in items">
<input type="checkbox"
ng-model="item.selected" ng-click="test(item.title)"> {{item.title}}
</div>
controller
$scope.test = function(vals) {
$scope.vl=[];
$scope.vlChecked=[];
for(var i=0;i<$scope.items.length;i++) {
if($scope.items[i].selected) {
$scope.vlChecked.push({
id: $scope.items[i].id,
title: $scope.items[i].title,
selected:true
});
}
}
console.log("vlChecked array");
console.log(JSON.stringify($scope.vlChecked));
}

passing object to angularjs directive from the controller

Trying to get my head around AngularJS directives. I need to pass a full object from my main controller to the directive. See the code below and jsfiddle: http://jsfiddle.net/graphicsxp/Z5MBf/4/
<body ng-app="myApp">
<div ng-controller="MandatCtrl">
<div person myPerson="mandat.person"></div>
<span>{{mandat.rum}}</span>
<span>{{mandat.person.firstname}}</span>
</div>
and the script:
var myApp = angular.module("myApp", []);
myApp.controller("MandatCtrl", function ($scope) {
$scope.mandat = { rum: "15000", person: { id: 1408, firstname: "sam" } };
});
myApp.directive("person", function () {
return {
scope: {
myPerson: "="
},
template: 'test: <div ng-model="myPerson"><input type="text" ng-model="firstname" /></div>'
}
});
Ok, the binding is working fine for mandat.rum and mandat.person.firstname.
However, I'm trying to pass mandat.person to the directive, and it does not work. I know I must be doing something wrong, the question is what ? :)
Pls see below working copy
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<span>{{mandat.rum}}</span>
<span>{{mandat.person.firstname}}</span>
<input type="text" ng-model="mandat.person.firstname" />
<my-directive mandateperson="mandat.person" >
</my-directive>
<script type="text/javascript">
var app = angular.module('plunker', []);
app.controller('MainCtrl', function ($scope) {
$scope.mandat = { name: "John", surname: "Doe", person: { id: 1408, firstname: "sam" } };
});
app.directive('myDirective', function () {
return {
restrict: 'E',
template: "<div><span>{{mandateperson.id}}<span><input type='text' ng-model='mandateperson.firstname' /></div>",
replace: true,
scope: { mandateperson: '=' }
}
}
)
</script>
</body>
</html>

Resources