Unable to update the `$scope` index value from DOM click - angularjs

In my directive, i have custom templates and replacing with existing one. when the custom templates click, i need to update the $scope.index to update.
but it's not working. but when i console the property it all works. what is the correct way to do this?
here is my custom directive:
var myApp = angular.module('myApp', []);
myApp.controller('main', function ($scope) {
$scope.values = [{"name":"one", "num" : 1}, {"name":"two", "num" : 2}, {"name":"three", "num" : 3}]
$scope.index = 0;
$scope.update = function (num) {
$scope.index = num;
}
});
myApp.directive("newArray", function ($compile) {
return {
scope : {
value : "=",
index : "=",
update:"&"
},
link : function (scope, element, attrs) {
var getTemplate = function (val, index) {
switch(index) {
case 0 :
return $('<div />', {
class:'red',
html : "<h1>testing</h1>",
click : function () {
console.log(scope.value.num); //works
scope.update(scope.value.num); //not wroking
}
});
break;
case 1 :
return $('<div />', {
class:'blue',
html : "<h1>testing</h1>",
click : function () {
scope.update(scope.value.num);
}
});
break;
case 2 :
return $('<div />', {
class:'green',
html : "<h1>testing</h1>",
click : function () {
scope.update(scope.value.num);
}
});
break;
}
}
element.html(getTemplate(scope.value, scope.index));
$compile(element.contents())(scope);
element.replaceWith(element.contents());
}
}
})
Live Demo

In the html change the line
<new-array index='$index' update="update" value='value' ng-repeat="value in values">{{value.name}}</new-array>
to
<new-array index='$index' update="update($index)" value='value' ng-repeat="value in values">{{value.name}}</new-array>
In the js change:
scope.update(scope.value.num);
to
scope.update({num: scope.value.num});
and finally change:
$scope.update = function (num) {
$scope.index = num;
}
to
$scope.update = function (num) {
$scope.index = num;
$scope.$apply();
}
See updated plunker

Related

AngularJS :wait in 'link' of directive is not working

In the below source, the watch method in the link part of a custom directive is not working. I use 'link' within the directive because I have to update the DOM structure.
How can I get the watch in the link{} of the directive working EACH time the button is pushed?
EDIT: I found the wrong code. See below 'ERROR' and 'CORRECT' code.
The HTML above this script is (click on a button to increment a variable):
<div ng-controller="AppController as vmx">
<button ng-click="vmx.incrementFoo()">Increment Foo</button>:
{{ vmx.fooCount }}.
<div foo-count-updated></div>
</div>
Angular code:
angular.module( "myapp", [])
.controller( "AppController", myAppController)
.directive('showAlsoInCustomDirective', showAlsoInCustomDirective);
// *** CONTROLLER
function myAppController( $scope ) {
var vm = this;
vm.fooCount = 0;
vm.copiedFooCount = 0;
// ERROR code:
// **vm.getFooCount** = function() {
// return vm.fooCount;
// }
// CORRECT code:
getFooCount = function() {
return vm.fooCount;
}
vm.getFooCount = getFooCount;
vm.incrementFoo = incrementFoo;
function incrementFoo() {
++vm.fooCount;
}
}
// *** DIRECTIVE
.directive('fooCountUpdated', fooCountUpdater);
function fooCountUpdater() {
var indirectivecounter = 0;
getFooCountInDirective = function() {
return getFooCount();
}
var watcherFn = function (watchScope) {
return getFooCountInDirective();
}
return {
link: function (scope, element, attrs) {
scope.$watch(watcherFn, function (newValue, oldValue) {
element.html( "Got the change: " + newValue);
})
}};
}
The complete source is put in this file:
https://plnkr.co/edit/J6nfLQ3dmLW0gDNXV0J5?p=preview
As indicated above, the solution was simple. It is also in the plunker file.
HTML:
<div ng-controller="AppController as vmx">
<button ng-click="vmx.incrementFoo()">Increment Foo</button>:
{{ vmx.fooCount }}.
<div foo-count-updated></div>
</div>
Angular code:
angular.module( "myapp", [])
.controller( "AppController", function( $scope ) {
var vm = this;
vm.fooCount = 0;
getFooCount = function() {
return vm.fooCount;
}
vm.getFooCount = getFooCount;
vm.incrementFoo = incrementFoo;
function incrementFoo() {
++vm.fooCount;
}
})
.directive('fooCountUpdated', fooCountUpdater);
function fooCountUpdater() {
var indirectivecounter = 0;
getFooCountInDirective = function() {
return getFooCount();
}
var watcherFn = function (watchScope) {
return getFooCountInDirective();
}
return {
link: function (scope, element, attrs) {
scope.$watch(watcherFn, function (newValue, oldValue) {
element.html( "Got the change: " + newValue);
})
}};
}

How to `$destroy` directive and replace with new values

I have 2 set of arrays. the first set is being as the default. when user click the next button, i need to update the new set. I can do this.
But the previous set as well exist. I don't know how to properly remove that, and define the new values. I am looking for the way that, which remove the event listner while remove the DOM. and memory leak should not be as well.
here is my js :
var myApp = angular.module('myApp', []);
myApp.controller('main', function ($scope) {
$scope.values = [{"name":"one", "num" : 1}, {"name":"two", "num" : 2}, {"name":"three", "num" : 3}];
$scope.next = function () {
$scope.index = 4;
$scope.values = [{"name":"four", "num" : 4}, {"name":"five", "num" : 5}, {"name":"six", "num" : 6}];
}
$scope.index = 0;
$scope.update = function (value) {
console.log("clicked " + value.num);
$scope.index = value.num;
$scope.$apply();
}
});
myApp.directive("newArray", function ($compile) {
return {
scope : {
value : "=",
index : "=",
update:"&"
},
link : function (scope, element, attrs) {
var getTemplate = function (value, index) {
switch(index) {
case 0 :
return '<div ng-click="update()">I am here {{index}} {{value.name}}</div>'
break;
case 1 :
return $('<div />', {
class:'blue',
html : "<h1>testing{{index}} {{value.name}}</h1>",
click : function () {
scope.update({num: scope.value.num});
}
});
break;
case 2 :
return $('<div />', {
class:'green',
html : "<h1>testing{{index}} {{value.name}}</h1>",
click : function () {
scope.update({num: scope.value.num});
}
});
break;
}
}
element.html(getTemplate(scope.value, scope.index));
$compile(element.contents())(scope);
element.replaceWith(element.contents());
}
}
});
Live Demo
updating my plnkr is appreciated. may help my future reference.
For such a different requirement I'll not go for the isolated scope directive that will mess up, As you want to use replace directive DOM with the the directive template. Another reason you are using ng-repeat on your directive which is not maintaining DOM structure in proper manner as you are replacing directive DOM with the newly constructed DOM. Instead of which I created a simple directive that do loop inside directive and create a element with new isolated scope & appending it to Pseudo element inside watcher.
Markup
<body ng-controller="main">
<a ng-click="next()" href="#">Next</a>
<h1>{{index}}</h1>
<new-array values='values'></new-array>
</body>
Directive
myApp.directive("newArray", function ($compile) {
return {
link : function (scope, element, attrs) {
var getTemplate = function (value, index) {
var newScope = scope.$new(true);
newScope.value = value;
switch(index) {
case 0 :
newScope.index = index;
return $compile('<div ng-click="$parent.update(value)">I am here {{value.num}} {{value.name}}</div>')(newScope)
break;
case 1 :
return $compile($('<div />', {
class:'blue',
html : "<h1>testing{{index}} {{value.name}}</h1>",
click : function () {
scope.update({num: scope.values[index].num});
}
}))(newScope);
break;
case 2 :
return $compile($('<div />', {
class:'green',
html : "<h1>testing{{index}} {{value.name}}</h1>",
click : function () {
scope.update({num: scope.values[index].num});
}
}))(newScope);
break;
}
}
scope.$watch('values', function(newVal){
var html = '', dom = $('<div/>');
element.empty();
for(var i=0;i < newVal.length; i++){
element.append(getTemplate(newVal[i], i))
}
//element.replaceWith(dom)
}, true);
}
}
})
Working Plunkr
Note
You can not really think of $destroy in your case. It just like
destructor which used to clear the events.

Decorating a directive by adding a function that will call the directive's controller

I use a directive that is declared like this :
(function (directives) {
var FilterDirective = (function () {
function FilterDirective() {
var directive = {};
directive.restrict = 'A';
directive.scope = true;
directive.controller = elasticui.controllers.FilterController;
directive.link = function (scope, element, attrs, filterCtrl) {
scope.$watch(element.attr('eui-filter') + " | euiCached", function (val) { return scope.filter.filter = val; });
var enabled = false;
var enabledAttr = element.attr('eui-enabled');
if (enabledAttr) {
scope.$watch(enabledAttr, function (val) { return scope.filter.enabled = val; });
enabled = scope.$eval(enabledAttr);
}
scope.filter = {
filter: scope.$eval(element.attr('eui-filter') + " | euiCached"),
enabled: enabled
};
filterCtrl.init();
};
return directive;
}
return FilterDirective;
})();
directives.FilterDirective = FilterDirective;
directives.directives.directive('euiFilter', FilterDirective);
})
The controller of the directive is :
(function (controllers) {
var FilterController = (function () {
function FilterController($scope) {
this.scope = $scope;
}
FilterController.prototype.init = function () {
var _this = this;
if (this.scope.filter.filter) {
var isEnabled = this.scope.filters.contains(this.scope.filter.filter);
if (!isEnabled && this.scope.filter.enabled) {
this.scope.filters.add(this.scope.filter.filter);
isEnabled = true;
}
}
this.scope.filter.enabled = isEnabled;
this.scope.$watch('filter.enabled', function (newVal, oldVal) {
if (newVal !== oldVal) {
_this.updateFilter();
}
});
this.scope.$watch('filter.filter', function (newVal, oldVal) {
if (!elasticui.util.EjsTool.equals(oldVal, newVal)) {
if (oldVal) {
_this.scope.filters.remove(oldVal);
}
_this.updateFilter();
}
});
};
FilterController.prototype.updateFilter = function () {
if (!this.scope.filter.filter) {
return;
}
if (this.scope.filter.enabled) {
this.scope.filters.add(this.scope.filter.filter);
}
else {
this.scope.filters.remove(this.scope.filter.filter);
}
};
FilterController.$inject = ['$scope'];
return FilterController;
})();
controllers.FilterController = FilterController;
})
Actually, the directive has a scope containing a filter object which contains two attributes filter : { enabled : boolean, filter : object} and the directive is used like this :
<label class="btn" ng-model="filter.enabled"
eui-filter="ejs.TermFilter('field','value')" btn-checkbox>
when the button is clicked the filter.enabled is set. My purpose is to add a behavior that will permit to change filter.enabled value via a function external to the directive.
The directive will look like this :
<label class="btn" ng-model="filter.enabled"
eui-filter="ejs.TermFilter('field','value')" eui-enable-fn="fn(somevariable)" btn-checkbox>
where fn will take the somevariable and set it to the filter.enabled.
Thanks in advance,
If you want to enable/disable a filter through the pressure of a button why not declare a filter with the property eui-enabled set to a custom toggling variable?
In other words it would result as:
HTML:
<label class="btn" eui-filter="..." eui-enabled="my_toggling_variable">
<button type=button ng-click="toggleVar()"></button>
JS:
myApp.controller('myCtrl', ['$scope', function($scope) {
$scope.my_toggling_variable = false;
$scope. toggleVar = function(){
$scope.my_toggling_variable = !$scope.my_toggling_variable;
};
}]);
Hope to have understood well the topic.

How to change the text of button three times in angular?

Hi Friends here i have done the code for change text of button, like if i press the button the text of the button will change. But i need the text of the button to be change one more time,
eg: initially "Button1" -->(click)-->"Button2" -->(click)-->"Button3".
I need button3 also.
please reffer:http://jsfiddle.net/Ljrpd/17/
var app = angular.module('my-app', [], function () {
})
app.controller('AppController', function ($scope) {
$scope.toggle = true;
$scope.$watch('toggle', function(){
$scope.toggleText = $scope.toggle ? 'Button1' : 'Button2';
})
})
Some one help me out in this issue.
Thanks
You don't need toggle variable, you can store selected index as suggested by Peter. I would also add check for last selection:
app.controller('AppController', function ($scope) {
$scope.buttonIndex = 0;
$scope.buttonNames = ['Button 1', 'Button 2', 'Button 3', 'Last Button']
$scope.changeText = function() {
if ($scope.buttonIndex === $scope.buttonNames.length - 1) {
$scope.buttonIndex = 0;
} else {
$scope.buttonIndex += 1;
}
};
});
JS Fiddle
Try my modification:
http://jsfiddle.net/Ljrpd/18/
<button ng-click="toggle = !toggle">{{buttonNames[buttonIndex]}}</button>
var app = angular.module('my-app', [], function () {
})
app.controller('AppController', function ($scope) {
$scope.toggle = true;
$scope.buttonIndex = 0;
$scope.buttonNames = ['first', 'second', 'third']
$scope.$watch('toggle', function(){
$scope.buttonIndex += 1;
})
})
And here's a version without a watch:
http://jsfiddle.net/russf6s9/1/
<button ng-click="incrementButton()">{{buttonNames[buttonIndex]}}</button>
var app = angular.module('my-app', [], function () {
})
app.controller('AppController', function ($scope) {
$scope.buttonIndex = 0;
$scope.incrementButton = function() {
$scope.buttonIndex += 1;
}
$scope.buttonNames = ['first', 'second', 'third']
})
Use a directive:
app.directive('changeText', function(){
return {
restrict: "A",
scope: {
changeText: "="
},
link: function(scope, element, attr) {
scope.index = 0;
element.html(scope.changeText[0]);
element.on('click', function(){
scope.index = (scope.index + 1) % scope.changeText.length;
element.html(scope.changeText[scope.index]);
})
}
};
})
Then in your html:
<body ng-controller="MainCtrl as ctrl">
<button change-text="ctrl.textValues"></button>
</body>
Plnkr
Script:
.controller('myctrl', function ($scope) {
$scope.btntext='button_1';
$scope.changetext = function () {
$scope.btntext = ($scope.btntext=='button_1')?'button_2':($scope.btntext=='button_2')?'button_3':'button_1';
}
});
Markup:
<input type="button" ng-click="changetext()" ng-value="btntext"/>
View in Plunker

AngularJS $watch newValue is undefined

I am trying to make a alert service with a directive. It is in the directive part I have some trouble. My have a directive that looks like this:
angular.module('alertModule').directive('ffAlert', function() {
return {
templateUrl: 'components/alert/ff-alert-directive.html',
controller: ['$scope','alertService',function($scope,alertService) {
$scope.alerts = alertService;
}],
link: function (scope, elem, attrs, ctrl) {
scope.$watch(scope.alerts, function (newValue, oldValue) {
console.log("alerts is now:",scope.alerts,oldValue, newValue);
for(var i = oldValue.list.length; i < newValue.list.length; i++) {
scope.alerts.list[i].isVisible = true;
if (scope.alerts.list[i].timeout > 0) {
$timeout(function (){
scope.alerts.list[i].isVisible = false;
}, scope.alerts.list[i].timeout);
}
}
}, true);
}
}
});
The reason for the for-loop is to attach a timeout for the alerts that has this specified.
I will also include the directive-template:
<div class="row">
<div class="col-sm-1"></div>
<div class="col-sm-10">
<div alert ng-repeat="alert in alerts.list" type="{{alert.type}}" ng-show="alert.isVisible" close="alerts.close(alert.id)">{{alert.msg}}</div>
</div>
<div class="col-sm-1"></div>
</div>
When I run this, I get this error in the console:
TypeError: Cannot read property 'list' of undefined
at Object.fn (http://localhost:9000/components/alert/ff-alert-directive.js:10:29)
10:29 is the dot in "oldValue.list" in the for-loop. Any idea what I am doing wrong?
Edit: I am adding the alertService-code (it is a service I use to keep track of all the alerts in my app):
angular.module('alertModule').factory('alertService', function() {
var alerts = {};
var id = 1;
alerts.list = [];
alerts.add = function(alert) {
alert.id = id;
alerts.list.push(alert);
alert.id += 1;
console.log("alertService.add: ",alert);
return alert.id;
};
alerts.add({type: "info", msg:"Dette er til info...", timeout: 1000});
alerts.addServerError = function(error) {
var id = alerts.add({type: "warning", msg: "Errormessage from server: " + error.description});
// console.log("alertService: Server Error: ", error);
return id;
};
alerts.close = function(id) {
for(var index = 0; index<alerts.list.length; index += 1) {
console.log("alert:",index,alerts.list[index].id);
if (alerts.list[index].id == id) {
console.log("Heey");
alerts.list.splice(index, 1);
}
}
};
alerts.closeAll = function() {
alerts.list = [];
};
return alerts;
});
try like this , angular fires your watcher at the first time when your directive initialized
angular.module('alertModule').directive('ffAlert', function() {
return {
templateUrl: 'components/alert/ff-alert-directive.html',
controller: ['$scope','alertService',function($scope,alertService) {
$scope.alerts = alertService;
}],
link: function (scope, elem, attrs, ctrl) {
scope.$watch(scope.alerts, function (newValue, oldValue) {
if(newValue === oldValue) return;
console.log("alerts is now:",scope.alerts,oldValue, newValue);
for(var i = oldValue.list.length; i < newValue.list.length; i++) {
scope.alerts.list[i].isVisible = true;
if (scope.alerts.list[i].timeout > 0) {
$timeout(function (){
scope.alerts.list[i].isVisible = false;
}, scope.alerts.list[i].timeout);
}
}
}, true);
}
}
});
if you have jQuery available, try this
if(jQuery.isEmptyObject(newValue)){
return;
}
inside scope.$watch

Resources