how to binding one way angular and binding again when model change? - angularjs

There are any solution or angular plug-in to do binding one way and binding again when model is change?
Now I'm using plug-in bind-once , But it just binding on first time and then it destroy watcher. Example:
<div bindonce="model"><span bo-bind="model.title"></span></div>

Angular already does this for you
<div><span ng-bind="model.title"></span></div>
or
<div><span>{{model.title}}</span></div>

how you can do it is: re-redner(ng-if) the page on change of certain variable. what would happen is, the
dom would be removed, and added again, which it is being added again : angular should bind the variable to its current value, so this way you get to keep bind-once and also update the value as per your need.
only caveat is, you would need an indicator for DOM on when to reload.
you can use the reload directive below(which I am using in my app):
csapp.directive("csReloadOn", ["$timeout", "Logger", function ($timeout, logManager) {
var $log = logManager.getInstance("csReloadOn");
var getTemplate = function () {
return '<div ng-if="doRefreshPageOnModeChange"><div ng-transclude=""></div></div>';
};
var linkFunction = function (scope, element, attrs) {
scope.doRefreshPageOnModeChange = true;
scope.$watch(attrs.csReloadOn, function (newVal, oldVal) {
if (newVal === oldVal) return;
$log.info("changed mode from : " + oldVal + ", to : " + newVal);
scope.doRefreshPageOnModeChange = false;
$timeout(function () { scope.doRefreshPageOnModeChange = true; }, 100);
});
};
return {
restrict: 'A',
transclude: true,
template: getTemplate,
link: linkFunction
};
}]);

Related

changing a controller scope variable in a directive is not reflected in controller function

In my directive, I have a controller variable, page which gets incremented when you press the button in the directive. However, the next line, scope.alertPage() which calls the controller function does not reflect this change. Notice, when you click the button page is still alerted as 1!
I know I can fix this by adding $scope.$apply in the controller but then I get the error that says a digest is already taking place.
Plunker
app = angular.module('app', []);
app.controller('myCtrl', function($scope) {
$scope.page = 1;
$scope.alertPage = function() {
alert($scope.page);
}
})
app.directive('incrementer', function() {
return {
scope: {
page: '=',
alertPage: '&'
},
template: '<button ng-click="incrementPage()">increment page</button>',
link: function(scope, elem, attrs) {
scope.incrementPage = function() {
scope.page += 1;
scope.alertPage();
}
}
}
})
html template:
<body ng-app='app' ng-controller='myCtrl'>
page is {{page}}
<incrementer page='page' alert-page='alertPage()'></incrementer>
</body>
The reason why it does not show the updated value immediately is because the 2 way binding updates the parent (or the consumer scope of the directive) scope's bound value only during the digest cycle. Digest cycle happens after the ng-click is triggered. And hence $scope.page in the controller is not yet updated. You can get around this in many ways by using a timeout which will defer the action to run at the end of the digest cycle. You could also do it by setting an object which holds the value as 2-way bound property. Since 2-way bound property and parent scope share the same object reference you will see the change immediately.
Method 1 - using a timeout:
scope.incrementPage = function() {
scope.page += 1;
$timeout(scope.alertPage)
}
Method 2 - Bind an object:
//In your controller
$scope.page2 = {value:1};
//In your directive
scope.incrementPage = function() {
scope.page.value += 1;
scope.alertPage();
}
Method3 - Pass the value using function binding with argument:
//In your controller
$scope.alertPage = function(val) {
alert(val);
}
and
<!--In the view-->
<div incrementer page="page" alert-page="alertPage(page)"></div>
and
//In the directive
scope.incrementPage = function() {
scope.page += 1;
scope.alertPage({page:scope.page});
}
app = angular.module('app', []);
app.controller('myCtrl', function($scope) {
$scope.page = 1;
$scope.page2 = {value:1};
$scope.alertPage = function() {
alert($scope.page);
}
$scope.alertPage2 = function() {
alert($scope.page2.value);
}
})
app.directive('incrementer', function($timeout) {
return {
scope: {
page: '=',
alertPage: '&',
page2:"=",
alertPage2: '&'
},
template: '<button ng-click="incrementPage()">increment page</button>',
link: function(scope, elem, attrs) {
scope.incrementPage = function() {
scope.page += 1;
scope.page2.value += 1;
$timeout(function(){ scope.alertPage() });
scope.alertPage2();
}
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<div incrementer page="page" alert-page="alertPage()" page2="page2" alert-page2="alertPage2()"></div>
</div>
You can pass the variable by reference, then the update will be immediate (because you wont copy it, but simply pass its location in memory).
View:
<incrementer page="data" alert-page='alertPage()'></incrementer>
Directive:
link: function(scope, elem, attrs) {
scope.incrementPage = function() {
scope.page.page += 1;
scope.alertPage();
}
The problem is that the timeline is off.
button clicked, incrementPage()
directive scope value incremented (now 2)
alertPage() parent scope value read (still 1)
parent scope updated as part of digest (now 2)
To get around this, you need to either call the alert function after the digest cycle (e.g. $timeout) or you need to watch for changes in the parent scope.
// in controller
$scope.$watch('page', function (currentValue, previousValue) {
// initially triggered with same value
if (currentValue > previousValue) {
alert(currentValue)
}
})
Then change the value naturally.
// in directive html
<button ng-click="page = page + 1">
Try doing this slightly differently. Pass in a function to do the increment rather than incrementing inside the directive
HTML
<incrementer page='incPage()' alert-page='alertPage()'></incrementer>
Controller
$scope.incPage = function() { // Function to increment
$scope.page++;
};
In Directive
scope: {
page: '&', // Receive like this
alertPage: '&'
},
link: function(scope, elem, attrs) {
scope.incrementPage = function() {
scope.page(); // Call as function
scope.alertPage();
}
}

ng-click toggle variable and update entire page

I have a global variable called RecruiterDashboard.IsColdList. It is a boolean that decides rather to run one directive or another. When the page is loaded the variable is made either true or false through normal scripting.
What I want to do is allow the user to toggle through an ng-click rather to show this other directive or not, so I made an ng-click and set RecruiterDashboard.IsColdList from 'false' to 'true'. Problem is this doesn't reload the angular page and fire the controllers off. How do make the page run through the controllers again?
This is what I have so far:
$scope.showColdList = function (projId) {
RecruiterDashboard.isColdList = true;
};
I want to point out that I am not using angular routing. I am using C# MVC.
My logic looks like so:
callPanelControllers.controller('callPanelController', function($scope) {
$scope.isColdList = RecruiterDashboard.isColdList;
});
callPanelControllers.controller('incomingCall', function ($scope) {
$scope.showColdList = function () {
RecruiterDashboard.isColdList = true;
};
});
<div ng-click="showColdList()" ng-controller="incomingCall"></div>
<div ng-controller="callPanelController">
<cold-list ng-show="isColdList"></cold-list>
</div>
i had developed sort of a hack, so that the entire content inside of a given element is reloaded on change of a certain variable.
csapp.directive("csReloadOn", ["$timeout", function ($timeout) {
var getTemplate = function () {
return '<div ng-if="doRefreshPageOnModeChange"><div ng-transclude=""></div></div>';
};
var linkFunction = function (scope, element, attrs) {
scope.doRefreshPageOnModeChange = true;
scope.$watch(attrs.csReloadOn, function (newVal, oldVal) {
if (newVal === oldVal) return;
scope.doRefreshPageOnModeChange = false;
$timeout(function () { scope.doRefreshPageOnModeChange = true; }, 100);
});
};
return {
restrict: 'A',
transclude: true,
template: getTemplate,
link: linkFunction
};
}]);
you can use it like
<div cs-reload-on="{{pagemode}}">
<!-- your html here-->
</div>
so it just removes and re-renders the complete content inside of the div, so everything is reinitialized etc etc.

Angular - How to "bind" when "oninput" with "contenteditable span"?

"<span contenteditable>{{ line.col2 }}</span>"
Hello,
This code is good at initialisation but if I edit the span, no bing is send and my array model never updated...
So, I have tried this :
<span contenteditable ng-model="line.col2" ng-blur="line.col2=element.text()"></span>
But "this.innerHTML" does not exist.
What can I do ?
Thank at all ;-)
you can remove the ng-blur and you will have to add this directive:
<span contenteditable ng-model="myModel"></span>
Here is the directive taken from the documentation:
.directive('contenteditable', function() {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$apply(read);
});
read(); // initialize
// Write data to the model
function read() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if( attrs.stripBr && html == '<br>' ) {
html = '';
}
ngModel.$setViewValue(html);
}
}
}
});
I only will point you to possible solution, then you need to parse/clean HTML better.
<span contenteditable data-ng-blur="bar = $event.target.innerHTML">
{{bar}}
</span>
// upd.
Angular events such as click, blur, focus, ... - fired with scope context, e.g. this will be current scope.
Use $event, be happy.
Solution with Mirrage and gab help :
<span contenteditable="true" ng-model="ligne.col2">{{ ligne.col2 }}</span>
app.directive('contenteditable', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
// view -> model
element.bind('blur', function() {
scope.$apply(function() {
ctrl.$setViewValue(element.html());
});
});
// model -> view
ctrl.$render = function() {
element.html(ctrl.$viewValue);
};
// load init value from DOM
ctrl.$render();
}
};
});
Thank at all ;-)

How do I properly set the value of my timepicker directive in AngularJS?

I'm trying to create a timepicker directive in AngularJS that uses the jquery timepicker plugin. (I am unable to get any of the existing angular TimePickers to work in IE8).
So far, I was able to get the directive to work as far as updating the scope when a time is selected. However, what I need to accomplish now is getting the input to display the time, rather than the text of the model's value when the page first loads. See below:
this is what shows:
this is what I want:
Here is my directive:
'use strict';
playgroundApp.directive('timePicker', function () {
return {
restrict: 'A',
require: "?ngModel",
link: function(scope, element, attrs, controller) {
element.timepicker();
//controller.$setViewValue(element.timepicker('setTime', ngModel.$modelValue));
//ngModel.$render = function() {
// var date = ngModel.$modelValue ? new Date(ngModel.$modelValue) : null;
//};
//if (date) {
// controller.$setViewValue(element.timepicker('setTime', date));
//}
element.on('change', function() {
scope.$apply(function() {
controller.$setViewValue(element.timepicker('getTime', new Date()));
});
});
},
};
})
The commented code is what I've attempted, but it doesn't work. I get an error that reads, ngModel is undefined. So, to clarify, when the page first loads, if there is a model for that input field, I want the input to show only the time, as it does after a value is selected.
Thanks.
EDIT:
Ok, after making some trial and error changes, my link function looks like this:
link: function (scope, element, attrs, controller) {
if (!controller) {
return;
}
element.timepicker();
var val = controller.$modelValue;
var date = controller.$modelValue ? new Date(controller.$modelValue) : null;
controller.$setViewValue(element.timepicker('setTime', controller.$modelValue));
//ngModel.$render = function () {
// var date = ngModel.$modelValue ? new Date(ngModel.$modelValue) : null;
//};
if (date) {
controller.$setViewValue(element.timepicker('setTime', date));
}
element.on('change', function() {
scope.$apply(function() {
controller.$setViewValue(element.timepicker('getTime', new Date()));
});
});
},
This doesn't give me any errors, but the $modelValue is always NaN. Here is my controller code:
$scope.startTime = new Date();
$scope.endTime = new Date();
and the relevant html:
<input id="startTime" ng-model="startTime" time-picker/>
<input id="endTime" ng-model="endTime" time-picker />
Is there something else I need to do?
I spent several days trying with the same plugin without getting results and eventually I found another:
http://trentrichardson.com/examples/timepicker/
It works perfectly using the following directive:
app.directive('timepicker', function() {
return {
restrict: 'A',
require : 'ngModel',
link : function (scope, element, attrs, ngModelCtrl) {
$(function(){
element.timepicker({
onSelect:function (time) {
ngModelCtrl.$setViewValue(time);
scope.$apply();
}
});
});
}
}
});
I hope you find useful.

Run $watch after custom directive

I'm writing a custom directive to validate some value in the scope. It should work like the required attribute, but instead of validating the input text, it's going to validate a value in the scope. My problem is that this value is set in a $scope.$watch function and this function runs after my directive. So when my directive tries to validate the value it has not been set yet. Is it possible to run the $watch code before running my custom directive?
Here is the code:
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
var keys = {
a: {},
b: {}
};
$scope.data = {};
// I need to execute this before the directive below
$scope.$watch('data.objectId', function(newValue) {
$scope.data.object = keys[newValue];
});
});
app.directive('requiredAttribute', function (){
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
var requiredAttribute = attr.requiredAttribute;
ngModel.$parsers.unshift(function (value) {
ngModel.$setValidity('requiredAttribute', scope[attr.requiredAttribute] != null);
return value;
});
}
};
});
<input type="text" name="objectId" ng-model="data.objectId" required-attribute="object" />
<span class="invalid" ng-show="myForm.objectId.$error.requiredAttribute">Key "{{data.objectId}}" not found</span>
And here is a plunker: http://plnkr.co/edit/S2NrYj2AbxPqDrl5C8kQ?p=preview
Thanks.
You can schedule the $watch to happen before the directive link function directly. You need to change your link function.
link: function(scope, elem, attr, ngModel) {
var unwatch = scope.$watch(attr.requiredAttribute, function(requiredAttrValue) {
if (requiredAttribute=== undefined) return;
unwatch();
ngModel.$parsers.unshift(function (value) {
ngModel.$setValidity('requiredAttribute', requiredAttrValue != null);
return value;
});
});
}
This approach will activate the $watch function inside the directive only once and will remove the watcher the first time your required scope variable is set.
There is also another approach where you parse the value and check it this way:
link: function(scope, elem, attr, ngModel) {
var parsedAttr = $parse(attr.requiredAttribute);
ngModel.$parsers.unshift(function (value) {
ngModel.$setValidity('requiredAttribute', parsedAttr(scope) != null);
return value;
});
}
Here you will need to use $parse AngularJS service. The difference here is that this will mark the input field as invalid without waiting for first value set on the required scope variable.
Both variants allow you to pass an expression instead of a simple variable name. This makes it possible to write something as required-attribute="object.var1.var2".
It really depends on what you need.

Resources