2 ways binding error into ng-repeat - angularjs

When trying to create dynamic directives into a ng-repeat with 2 way binding, they dont render, the case goes as follow:
<div ng-controller='initCtrl'>
<navigation>
<div ng-repeat="item in items">
<item value="{{item.item}}" app="{{item.app}}"></item>
</div>
</navigation>
</div>
app.controller('initCtrl', function($scope) {
$scope.items = [
{name: 'andres', app: 'appcontroller'},
{name: 'julio', app:'appcontroller'},
{name: 'master', app: 'appcontroller'}
];
$scope.appcontroller = {
method: 'some string'
};
});
//my directives
app.directive('navigation', function(){
return {
strict: 'E',
transclude: true,
template: '<div class="panel"><div ng-transclude></div></div>'
};
});
app.directive('item', function() {
return {
strict: 'E',
require: '^navigation',
scope: {
value: '#',
app: '='
},
template: '<div class="item">{{ value }} and {{ app.method }}</div>'
};
});
The app attribute should be a two way biding which looks for the obj in the parent controller, however, I think the string generate into app is causing error.
What do u guys think?

When you are using app: '=' in directive definition there is not need in {{}} when you are passing attribute value. Passed value will be executed anyway. Working code:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.js"></script>
</head>
<body ng-app="app">
<div ng-controller='initCtrl'>
<navigation>
<div ng-repeat="item in items">
<item value="{{item.name}}" app="item.app"></item>
</div>
</navigation>
</div>
<script>
var app = angular.module('app', []);
app.controller('initCtrl', function($scope) {
$scope.items = [
{name: 'andres', app: 'appcontroller'},
{name: 'julio', app: 'appcontroller'},
{name: 'master', app: 'appcontroller'}
];
$scope.appcontroller = {
method: 'some string'
};
});
//my directives
app.directive('navigation', function() {
return {
strict: 'E',
transclude: true,
template: '<div class="panel"><div ng-transclude></div></div>'
};
});
app.directive('item', function() {
return {
strict: 'E',
require: '^navigation',
scope: {
value: '#',
app: '='
},
template: '<div class="item">{{ value }} and {{ app }}</div>'
};
});
</script>
</body>
</html>

Related

Angular1 Send Variable to directive

How can I send variable to directive? My code actually doesn't work, but I did everything from your comments :(
As you can see in my .html file, {{ ctrl.emptyParent.name }} is working.
.html
<div cms-dropdown emptyParent="emptyParent.name" classes="btn-default">
<i style="opacity: 0.8">{{ emptyParent.name }}</i>
</div>
directive
.directive('cmsDropdown', [function(){
return {
restrict: 'A',
scope: {
emptyParent: '=',
},
transclude: true,
template:
`
{{emptyParent}} Hi
`
link: function($scope, $element, $attrs){
}
};
}]);
and variable
this.emptyParent = {
_id: 'empty',
name: '~~#(brak)#~~',
parentAlbumId: null,
position: -1,
createdDate: undefined,
modifiedDate: undefined
};
change emptyParent="emptyParent.name" to empty-parent="emptyParent.name"
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.emptyParent = {"name":"jhon"}
})
.directive('cmsDropdown', [function(){
return {
restrict: 'A',
scope: {
emptyParent: '=',
},
transclude: true,
template:
`
{{emptyParent}} Hi
`,
link: function($scope, $element, $attrs){
}
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div cms-dropdown empty-parent="emptyParent.name" classes="btn-default">
<i style="opacity: 0.8">{{ emptyParent.name }}</i>
</div>
</div>

Angular directive scope - template include vs inline transclude

I have an angular directive for displaying a modal window. It can accept the contents either inline between the HTML tags, or be pointed to a template. When using this directive I seem to have normal access to the $scope when I am using the transcluded inline version of this directive, but when I use a template I do not.
What am I missing here? I've made a smaller sample directive that has the same behavior.
Demo: http://fiddle.jshell.net/ahezfaxj/2
Inline Content Usage
<ang-test show="showBoolean">
<p>Content here!</p>
</ang-test>
Template Usage
<ang-test show="showBoolean" template="'myTemplate.html'"></ang-test>
Directive
app.directive("angTest", function () {
return {
template: function () {
return "<div class='test-container'>" +
" <div ng-if='show && template' ng-include='template'></div>" +
" <div ng-if='show && !template' ng-transclude></div>" +
"</div>";
},
restrict: "E",
replace: true,
transclude: true,
scope: {
template: "#",
show: "="
},
link: function ($scope, $element, attrs) {
if(value){
$element[0].style.display="block";
}else{
$element[0].style.display="none";
}
}
};
});
Please see demo below. You created isolated scope in your directive thus your directive scope is not this same as controller $scope. But you can add as well thing to your directive scope like in example below.
I hope that will help.
var app = angular.module("app", []);
app.controller("BaseCtrl", function ($scope) {
$scope.thing = "Hello!";
$scope.showOne=false;
$scope.showTwo=false;
});
app.directive("angTest", function () {
return {
template: function () {
return "<div class='test-container'>" +
" <div ng-if='show && template' ng-include='template'></div>" +
" <div ng-if='show && !template' ng-transclude></div>" +
"</div>";
},
restrict: "E",
replace: true,
transclude: true,
scope: {
template: "#",
show: "=",
thing:'#'
},
link: function ($scope, $element, attrs) {
//Show/hide when `show` changes
$scope.$watch("show", function (value) {
if(value){
$element[0].style.display="block";
}else{
$element[0].style.display="none";
}
});
}
};
});
.test-container{
padding:5px;
background: #EEE;
}
.transcluded {
color:red
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="BaseCtrl">
Outside Directive: <strong>{{thing}}</strong>
<hr />
<button type="button" ng-click="showOne=!showOne">Toggle One</button>
<ang-test show="showOne">
<p class="transcluded">Inside Included Directive: <strong>--> thing transcluded-->{{thing}}</strong></p>
</ang-test>
<hr />
<script type="text/ng-template" id="myTemplate">
<p>Inside Template Directive: <strong>thing from directive scope -->{{thing}}</strong></p>
</script>
<button type="button" ng-click="showTwo=!showTwo" >Toggle Two</button>
<ang-test show="showTwo" template="myTemplate" thing="{{thing}}"></ang-test>
</div>
</div>

How to use checklistbox in angularjs or in bootstrap

Can anyone suggest me how can I display a checkbox list in angularjs
HTML:
<div ng-app="app">
<div ng-controller="TodoCtrl">
<span ng-repeat="(checkboxName, checkboxValue) in checkboxes">
{{ checkboxName }}
<input type="checkbox" ng-model="checkboxValue"/>
</span>
</div>
</div>
Javascript:
var app = angular.module('app', []);
app.controller('TodoCtrl', function($scope) {
$scope.checkboxes = {
'foo': true,
'bar': false,
'baz': true,
'baa': true
}
});
Update:
HTML:
<div ng-app="app">
<div ng-controller="TodoCtrl">
<!--<span ng-repeat="(checkboxName, checkboxValue) in checkboxes">
{{ checkboxName }}
<input type="checkbox" ng-model="checkboxValue"/>
</span>-->
<checklist checkboxes="checkboxes" on-change="checkboxInfo(name, value)"></checklist>
</div>
</div>
Javascript:
var app = angular.module('app', []);
app.controller('TodoCtrl', function($scope) {
$scope.foo = true;
$scope.bar = false;
$scope.baz = true;
$scope.baa = true;
$scope.checkboxes = {
'foo': $scope.foo,
'bar': $scope.bar,
'baz': $scope.baz,
'baa': $scope.baa
};
// Non-encapsulated activity: updates parent scope values
$scope.checkboxInfo = function(name, value) {
console.log('Checkbox "' + name + '" clicked. It is now: ' + value + '.');
$scope[name] = value;
};
// This shouldn't do anything if we delete '$scope[name] = value', since we isolated the scope:
$scope.$watchCollection('[foo, bar, baz, baa]', function() {
console.log($scope.foo, $scope.bar, $scope.baz, $scope.baa);
});
})
.directive('checklist', function($timeout) {
return {
restrict: 'E',
scope: {
checkboxes: '=', // create an isolate scope w/ 2-way binding
onChange: '&' // execute a function in the parent scope
},
template:
'<span ng-repeat="(checkboxName, checkboxValue) in checkboxes">' +
'{{ checkboxName }}' +
'<input type="checkbox" ng-model="checkboxValue" ng-change="onChange({name:checkboxName, value:checkboxValue})"/>' +
'</span>',
link: function(scope, element, attrs) {
// Add encapsulated activity as necessary
}
};
});

Pass object to custom angular bootstrap ui tooltip

Im trying to pass and object to a custom angular-ui bootstrap tooltip component.
My code so far is a new directive:
angular.module('ui.bootstrap.korv', [ 'ui.bootstrap.tooltip' ])
.directive('korvPopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { title: '#', content: '#', placement: '#', animation: '&', isOpen: '&', species: '='},
templateUrl: 'korv.html'
};
})
.directive('korv', [ '$tooltip', function ($tooltip) {
return $tooltip('korv', 'korv', 'click');
}]);
and the the template:
<script type="text/ng-template" id="korv.html">
<div class="tooltip {{ placement }}" ng-class="{ in: isOpen(), fade: animation() }">
<div class="tooltip-arrow"></div>
<div class="tooltip-inner">obj is {{content}} obj.a is {{content.a}}</div>
</div>
and in the view:
<li korv="{a:1234}">
outputs:
obj is {a:1234} obj.a is
So the object I pass converts to a json string and I can not access its fields. Using tooltipHtmlUnsafe is not an option here.
I tried changing content: '#' to content: '=' but that doesn't work.
So how can I pass an object to tooltip?
This is not possible due to the implementation of angular bootstrap ui tooltip. My solution was to create a new directive:
angular.module('app').directive('speciesInfo', function ($log, $timeout) {
return {
restrict: 'A', // only activate on element attribute
scope: {
species: "=speciesInfo"
},
link: function (scope, elem, attrs) {
var showPromise;
elem.on('mouseenter', function () {
showPromise = $timeout(function () {
elem.children('.popover').show();
}, 500);
});
elem.on('mouseleave', function () {
$timeout.cancel(showPromise);
elem.children('.popover').hide();
});
},
templateUrl: 'species-info.html'
}
});
now it is easy to style the tooltip:
<div class="popover right in fade">
<div class="arrow"></div>
<div class="popover-inner">
<div class="popover-title text-center">
{{species.vernacularName}} <img class="small-species" ng-src="{{species.iconFileName}}"/>
</div>
<div class="popover-content">
<em> {{species.scientificName}}</em>
</div>
</div>

Angular.js directive dynamic templateURL

I have a custom tag in a routeProvider template that that calls for a directive template. The version attribute will be populated by the scope which then calls for the right template.
<hymn ver="before-{{ week }}-{{ day }}"></hymn>
There are multiple versions of the hymn based on what week and day it is. I was anticipating to use the directive to populate the correct .html portion. The variable is not being read by the templateUrl.
emanuel.directive('hymn', function() {
var contentUrl;
return {
restrict: 'E',
link: function(scope, element, attrs) {
// concatenating the directory to the ver attr to select the correct excerpt for the day
contentUrl = 'content/excerpts/hymn-' + attrs.ver + '.html';
},
// passing in contentUrl variable
templateUrl: contentUrl
}
});
There are multiple files in excerpts directory that are labeled before-1-monday.html, before-2-tuesday.html, …
emanuel.directive('hymn', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
// some ode
},
templateUrl: function(elem,attrs) {
return attrs.templateUrl || 'some/path/default.html'
}
}
});
So you can provide templateUrl via markup
<hymn template-url="contentUrl"><hymn>
Now you just take a care that property contentUrl populates with dynamically generated path.
You can use ng-include directive.
Try something like this:
emanuel.directive('hymn', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
scope.getContentUrl = function() {
return 'content/excerpts/hymn-' + attrs.ver + '.html';
}
},
template: '<div ng-include="getContentUrl()"></div>'
}
});
UPD. for watching ver attribute
emanuel.directive('hymn', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
scope.contentUrl = 'content/excerpts/hymn-' + attrs.ver + '.html';
attrs.$observe("ver",function(v){
scope.contentUrl = 'content/excerpts/hymn-' + v + '.html';
});
},
template: '<div ng-include="contentUrl"></div>'
}
});
Thanks to #pgregory, I could resolve my problem using this directive for inline editing
.directive("superEdit", function($compile){
return{
link: function(scope, element, attrs){
var colName = attrs["superEdit"];
alert(colName);
scope.getContentUrl = function() {
if (colName == 'Something') {
return 'app/correction/templates/lov-edit.html';
}else {
return 'app/correction/templates/simple-edit.html';
}
}
var template = '<div ng-include="getContentUrl()"></div>';
var linkFn = $compile(template);
var content = linkFn(scope);
element.append(content);
}
}
})
You don't need custom directive here. Just use ng-include src attribute. It's compiled so you can put code inside. See plunker with solution for your issue.
<div ng-repeat="week in [1,2]">
<div ng-repeat="day in ['monday', 'tuesday']">
<ng-include src="'content/before-'+ week + '-' + day + '.html'"></ng-include>
</div>
</div>
I had the same problem and I solved in a slightly different way from the others.
I am using angular 1.4.4.
In my case, I have a shell template that creates a CSS Bootstrap panel:
<div class="class-container panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">{{title}} </h3>
</div>
<div class="panel-body">
<sp-panel-body panelbodytpl="{{panelbodytpl}}"></sp-panel-body>
</div>
</div>
I want to include panel body templates depending on the route.
angular.module('MyApp')
.directive('spPanelBody', ['$compile', function($compile){
return {
restrict : 'E',
scope : true,
link: function (scope, element, attrs) {
scope.data = angular.fromJson(scope.data);
element.append($compile('<ng-include src="\'' + scope.panelbodytpl + '\'"></ng-include>')(scope));
}
}
}]);
I then have the following template included when the route is #/students:
<div class="students-wrapper">
<div ng-controller="StudentsIndexController as studentCtrl" class="row">
<div ng-repeat="student in studentCtrl.students" class="col-sm-6 col-md-4 col-lg-3">
<sp-panel
title="{{student.firstName}} {{student.middleName}} {{student.lastName}}"
panelbodytpl="{{'/student/panel-body.html'}}"
data="{{student}}"
></sp-panel>
</div>
</div>
</div>
The panel-body.html template as follows:
Date of Birth: {{data.dob * 1000 | date : 'dd MMM yyyy'}}
Sample data in the case someone wants to have a go:
var student = {
'id' : 1,
'firstName' : 'John',
'middleName' : '',
'lastName' : 'Smith',
'dob' : 1130799600,
'current-class' : 5
}
I have an example about this.
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container-fluid body-content" ng-controller="formView">
<div class="row">
<div class="col-md-12">
<h4>Register Form</h4>
<form class="form-horizontal" ng-submit="" name="f" novalidate>
<div ng-repeat="item in elements" class="form-group">
<label>{{item.Label}}</label>
<element type="{{item.Type}}" model="item"></element>
</div>
<input ng-show="f.$valid" type="submit" id="submit" value="Submit" class="" />
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.10.2.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.2/angular.min.js"></script>
<script src="app.js"></script>
</body>
</html>
angular.module('app', [])
.controller('formView', function ($scope) {
$scope.elements = [{
"Id":1,
"Type":"textbox",
"FormId":24,
"Label":"Name",
"PlaceHolder":"Place Holder Text",
"Max":20,
"Required":false,
"Options":null,
"SelectedOption":null
},
{
"Id":2,
"Type":"textarea",
"FormId":24,
"Label":"AD2",
"PlaceHolder":"Place Holder Text",
"Max":20,
"Required":true,
"Options":null,
"SelectedOption":null
}];
})
.directive('element', function () {
return {
restrict: 'E',
link: function (scope, element, attrs) {
scope.contentUrl = attrs.type + '.html';
attrs.$observe("ver", function (v) {
scope.contentUrl = v + '.html';
});
},
template: '<div ng-include="contentUrl"></div>'
}
})

Resources