I am new to AngualrJS and I am having trouble getting a ng-click working inside a ng-repeat that sits inside a directive.
I use ng-repeat to display a list of PDFs and currently just trying to be able to click them to pop up an alert window. But I don't seem to be able to get any ng-click working within the directive.
The Angular code:
var app = angular.module("aria", []);
app.directive("rdnglist", function(){
return {
restrict: 'E',
templateUrl: "rdnglist.html",
controller: function(){
this.pdfs = pdflist;
this.test = function() {
$window.alert("hi");
};
},
controllerAs: "plist",
};
});`
The HTML:
<div class="fullsect">
<div class="pdflist" ng-repeat="pdf in plist.pdfs">
<h3>{{pdf.name}}</h3>
<img ng-src="{{pdf.image}}" ng-click="test()"/>
<p>Class: {{pdf.class}}</p>
<div id="commentNo">{{pdf.comments}}</div>
</div>
<div class="pdflist">
<h3>New File</h3>
<a ng-click="test()">Open</a>
<img src="/pictures/addnew.png"/>
</div>
I assume it has something to do with the scope of the controller but I'm unsure. As I'm new, I learned to use ControllerAs over $scope, is this the issue?
Here is a working plunker based on your code.
I changed the directive to inject $window ... see ['$window, function($window) to make the alert work. I also initialize with dummy data:
The app:
var app = angular.module('plunker', []);
app.directive("rdnglist", ['$window', function($window){
return {
restrict: 'E',
templateUrl: "rdnglist.html",
controller: function(){
this.pdfs = [{'name':'abc'}];
this.test = function() {
$window.alert("hi");
};
},
controllerAs: "plist",
};
}]);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
And the rdnglist.htm... as you are using ControllerAs, you need plist.test(). To reduce my work I hardcoded an AngularJS image:
<div class="fullsect">
<div class="pdflist" ng-repeat="pdf in plist.pdfs">
<h3>{{pdf.name}}</h3>
<a ng-click="plist.test()"><img ng-src="http://code-maven.com/img/angularjs.png" /></a>
<p>Class: {{pdf.class}}</p>
<div id="commentNo">{{pdf.comments}}</div>
</div>
<div class="pdflist">
<h3>New File</h3>
<a ng-click="test()">Open</a>
<img src="/pictures/addnew.png"/>
</div>
</div>
index.html:
<!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.9/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<rdnglist></rdnglist>
</body>
</html>
let us know if that helps.
Related
I want to have particular variable for menu to know which class to be active. Up to now I know how to set variable inside ng-view but I want to keep my menu out of that view. If I set variable in function in controller isn't visible outside of ng-view and that is exactly what I want to, to be visible. I try with rootscoope but I couldn't manage. If someone can help me my code is like this:
index.html
<!DOCTYPE html>
<html lang="en" ng-app="example">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="libs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/font-awesome.min.css" rel="stylesheet">
<link href="assets/css/main.css" rel="stylesheet">
<title>Example</title>
</head>
<body>
<div class="container-fluid main-header">
<div class="main-menu-active">First page</div>
<div class="main-menu">Second page</div>
</div>
<div ng-view class="main-body"></div>
<script src="libs/jquery/dist/jquery.min.js"></script>
<script src="libs/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="libs/angular/angular.min.js"></script>
<script src="libs/angular-route/angular-route.min.js"></script>
<link href="libs/ng-dialog/css/ngDialog.min.css" rel="stylesheet">
<link href="libs/ng-dialog/css/ngDialog-theme-default.css" rel="stylesheet">
<script src="libs/ng-dialog/js/ngDialog.js"></script>
<script src="app/app.js"></script>
<script src="app/controllers/mainCtr.js"></script>
</body>
</html>
app.js
(function () {
'use strict';
angular
.module('example', ['ngRoute','ngDialog'])
.config(function ($routeProvider,$httpProvider) {
$routeProvider.when('/', {
controller: 'mainCtr',
controllerAs: 'mCtr',
templateUrl: 'app/views/firstPage.html'
});
$routeProvider.when('/second', {
controller: 'mainCtr',
controllerAs: 'mCtr',
templateUrl: 'app/views/secondPage.html'
});
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
}).run(function($http, $httpParamSerializerJQLike) {
//decode json on every submit form
$http.defaults.transformRequest.unshift($httpParamSerializerJQLike);
})
})();
controller:
(function() {
'use strict';
angular
.module('example')
.controller('mainCtr', mainCtr);
mainCtr.$inject = ['$window','$routeParams','ngDialog','$timeout'];
function mainCtr($window,$routeParams,ngDialog,$timeout) {
var vm = this;
vm.firstPage = firstPage;
vm.secondPage = secondPage;
function firstPage() {
vm.test = 'This is first page';
}
function secondPage() {
vm.test = 'This is second page';
}
}
})();
I want to have access to variable vm.test in <div class="container-fluid main-header">
I would make a Controller around the ng-view which hold the value(s):
<body ng-controller="OuterController">
<div class="container-fluid main-header">
<div class="main-menu-active">First page</div>
<div class="main-menu">Second page</div>
</div>
<div ng-view class="main-body"></div>
...
</body>
and if you want to share data between the controllers in ng-view directive use a service.
So I've made a plunker to illustrate, how data sharing is accomplished: https://plnkr.co/edit/axekEgrFwnm93aFXoMKd
So the basic idea is to use a service and in someway either by button click as in the question or automatically in contoller as plunker, set the shared value.
Service
app.service('commonInfomation', function() {
return {
test: ''
};
});
Inner controller
app.controller('FirstCtrl', function($scope, commonInfomation) {
commonInfomation.test = "Hello from first page";
});
Outer controller
app.controller('MainCtrl', function($scope, commonInfomation) {
$scope.commonInfomation = commonInfomation;
});
View
<body ng-controller="MainCtrl">
<h2>{{commonInfomation.test}}</h2>
<div class="container-fluid main-header">
<a href="#/">
<div class="main-menu-active">First page</div>
</a>
<a href="#/second">
<div class="main-menu">Second page</div>
</a>
</div>
<div ng-view class="main-body"></div>
</body>
Module
var app = angular.module('plunker', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'firstpage.html',
controller: 'FirstCtrl'
})
.when('/second', {
templateUrl: 'secondpage.html',
controller: 'SecondCtrl'
})
});
I want to use Angular to create a popover that contains a <textarea> and a <button> to perform an action.
I followed this guide to create my popover with a custom directive.
My problem is that the content in the popover doesn't appear to be attached to the main controller anymore when it is inserted. The contents of the <textarea> does not display with {{ textarea }}, and the ng-click="click()" does not trigger the $scope.click function defined in the controller.
Maybe this is due to the fact that the content of the popover is being set in the directive, instead of being declared in the view1.html document? Any help would be appreciated.
I've made this JSFiddle which demonstrates the issue - it is very slightly simplified from the code below, but the problem is demonstrated just fine.
directives.js:
module.directive('customPopover', [function(){
return {
restrict: 'A',
link: function (scope, el, attrs) {
$(el).popover({
trigger: attrs.popoverTrigger,
html: true,
content: function() {return $('#popover_content').html();},
placement: attrs.popoverPlacement
});
}
};
}]);
pages/view1.html:
<div>
<div id="controls">
<a custom-popover class="btn"
tabindex="0"
popover-html="copyPaste"
popover-placement="right"
popover-trigger="click"
role="button">Copy & paste data</a>
</div>
<div id="popover_content" style="display:none;">
<textarea id="textBox" type="text" ng-model="textarea"></textarea>
<button id="submitDataBtn" ng-click="click()" type="button">Submit</button>
</div>
{{ textarea }}
</div>
controller.js
var module = angular.module("moduleName", ['ngRoute']);
module.controller("SimpleController", function ($scope, gsatfFactory, $sce, $location) {
$scope.click = function() {
$scope.table = $sce.trustAsHtml(gsatfFactory.parseData($scope.textarea));
$location.path('view2');
};
});
module.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/view1.html',
controller: 'SimpleController'
})
.when('/view2', {
templateUrl: 'pages/view2.html',
controller: 'SimpleController'
})
.otherwise({ redirectTo: '/' });
}]);
index.html
<!DOCTYPE html>
<html ng-app="moduleName">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
crossorigin="anonymous"></script>
<script src="js/controller.js"></script>
<script src="js/factory.js"></script>
<script src="js/directives/directives.js"></script>
</head>
<body>
<div data-ng-view></div>
</body>
</html>
Your content html isn't angular compiled. Use this to compile it:
$compile($('#popover_content').html())(scope);
your directive:
mod.directive('customPopover', function($compile){
return {
restrict: 'A',
link: function (scope, el, attrs) {
$(el).popover({
trigger: attrs.popoverTrigger,
html: true,
content: function() {return $compile($('#popover_content').html())(scope);},
placement: attrs.popoverPlacement
});
}
};
});
I've managed to load all my images from my json file into the application but i would only like 1 image to be loaded. I'm using ng-repeat which is why it keeps repeating itself. What do i replace ng-repeat with so it only shows the first image?
Here's my code.
Html:
<div ng-click="onClick()">
<i class="ion-images"></i>
</div>
<a ng-controller="Ctrl">
<ion-scroll direction="x">
<img on-hold="onHold()" ng-repeat="image in data" ng-src="{{image.image}}" />
</ion-scroll>
</a>
js:
.controller("Ctrl", function($scope, $http, $ionicModal) {
$scope.data = [];
$http.get('')
.success(function(data) {
$scope.data = data;
window.localStorage.setItem("images", JSON.stringify(data));
})
});
If you want display only first element from your array you don't have use ng-repeater, you can access it using array index ie:
ng-src="{{data.under9s[0].image}}
Please see working demo below:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.data = [];
$http.get('https://api.myjson.com/bins/4tutm')
.success(function(data) {
$scope.data = data;
window.localStorage.setItem("images", JSON.stringify(data));
})
.error(function(error) {
if (window.localStorage.getItem("images") !== undefined) {
$scope.data = JSON.parse(window.localStorage.getItem("images"));
}
});
});
<!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.3/angular.js" data-semver="1.4.3"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<ion-scroll direction="x">
<img on-hold="onHold()" ng-src="{{data.under9s[0].image}}" ng-click="showImages($index)" class="image-list-thumb" />
</ion-scroll>
</body>
</html>
So I can't really get this to work, I've got the following code
HTML:
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css">
<script>document.write("<base href=\"" + document.location + "\" />");</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
{{vt.t}}
<div my-directive="{{vt.t}}"></div>
{{vt.f}}
<div my-directive="{{vt.f}}"></div>
<hr />
{{vt.t}}
<div ng-class="{'my-directive': vt.t}"></div>
{{vt.f}}
<div ng-class="{'my-directive': vt.f}"></div>
<hr />
<div class="my-directive"></div>
<div class="nodirectiveclass"></div>
</body>
</html>
JavaScript:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.vt = { t: true, f: false };
});
app.directive('myDirective', function($compile) {
return {
restrict: 'AC',
template: '<div>Directive on</div>',
replace: true
};
});
Plunker: http://plnkr.co/edit/7cJKhIuNqnsk1CkczjoE?p=preview
As you see the classes doesn't trigger the directive when added dynamically but works fine in my last "static" example. I also tried setting the directive attribute to true or false but that didn't seem to help.
I think you should use model variable in your directive. Then you can access what ever the value you want easily.
Refer this Answer:
AngularJS - Create a directive that uses ng-model
Let say I have a controller and many children DOMs with their own data attributes.
<!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.2.x" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p data-test-val='Brian'>Hello {{name}}!</p>
</body>
</html>
I want to access to the data-test-val like this
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $attrs) {
$scope.name = $attrs.testVal;
});
However, it does not seem to work as name is empty.
http://plnkr.co/edit/V1Leit8U7r2k4CZDGaGa?p=preview
How to access any data attribute in children DOM of the same scope?
Thanks.
you're messing up controllers with directives in terms of attribute acquiration.
directive:
.directive('directiveName', function() {
return {
link: function($scope, $elem, $attrs) {
// get $attrs stuff here
}
}
});
Create a separate directive named as "dataTestVal", then you can get an access to attributes of the tag.
Example Code:
<html ng-app="ExampleApp">
<head>
//required libraries, scripts
</head>
<body ng-controller="ExCtrl">
<div data-testval data="person"></div>
</body>
<script>
angular.module('ExampleApp',[]);
angular.module('ExampleApp")
.controller("ExCtrl",function($scope){
$scope.person = {
name:"afd",
age : 30
};
});
angular.module('ExampleApp")
.directive("dataTextval",function(){
return{
restrict:'A',
scope:{
data : '='
},
link:function(scope,element,attrs){
//you can gain access to element and its attributes
//scope.data is nothing but person details, which is declared in controller
}
}
});
</script>
</html>
Try this :
var ele = document.getElementsByTagName('p');
$scope.name = ele.getAttribuete('data-test-val');