How to check the value of a variable in my case? - javascript

I am using Angular framework and I need to see if the data variable is changed when I click the button.
For example
<button ng-click='change()'>{{data}}</button>
I was hoping to see if data change or console log the data variable.
Currently its not working and might have a bug.
Can I do something like following:
<button ng-click='change()'>{{data; console.log(data)}}</button>
Thanks for the help.
Edit:
<div ng-app='myApp'>
<button ng-click='change()'>{{data}}</button>
</div>
var app = angular.module('myApp', [])
.controller('Ctrl', ['$scope', function ($scope) {
$scope.data='5'; //this shows correctly.
$scope.change=function(index){
$scope.data = '10'; //doesn't change after I click.
}

{{ data }} is a view binding expression. It simply prints out the value of the expression based on objects/properties in its scope.
If you want to log something on change then you can accomplish that within your change() function as defined in your controller.
The value displayed in your HTML will be the up-to-date value of data in that controller's scope.

Related

Angular JS update ng-click event on other click not working

I want to update argument of ng-click of button but not able to do it please help me... my code is
in controller
$scope.trCategoryId = 0;
and setting up this value in other function like
$scope.setClick = function (CategoryId) {
$scope.trCategoryId = CategoryId;}
in html i have define bellow
<button ng-click="ActiveTag('step1',{{trCategoryId}},0)" id="btnrename">Create</button>
it is not calling up ActiveTag function
Glad my comment worked out for you, adding it below as a solution:
Angular related attributes prefaced with ng- auto evaulate so
{{trCategoryId}} within any ng- is a no-no. It evaluates variable names against scope inside automatically, no need for the {{}}.
<button ng-click="ActiveTag('step1',trCategoryId,0)" id="btnrename">Create</button>

AngularJS: Share data between different controllers

I have the following structures
<div ng-controller='ctrlA'>
<button ng-click='updateFactoryData(data)'></button>
<custom-dir>Custom directive with ctrlB</custom-dir>
<custom-dir>Custom directive with ctrlB</custom-dir>
<custom-dir>Custom directive with ctrlB</custom-dir>
...
<other-custom-dir>Custom directive with ctrlC</other-custom-dir>
<other-custom-dir>Custom directive with ctrlC</other-custom-dir>
<other-custom-dir>Custom directive with ctrlC</other-custom-dir>
...
</div>
I have a dataFactory, which when user clicks the button, the updated data will store in dataFactory, the dataFactory is injected to both ctrlB and ctrlC.
The problem is, when data is updated after clicking the button, the changes do not reflect on both custom-dir and other-custom-dir, is there any way ctrlB and ctrlC's scope value automatically reflect the changes made in scope under ctrlA?
Thanks very much for the help!
Thanks all for the kind help!! I finally figure out why the change cannot be reflected, I watch the object parameter to see if there are changes, but watch only monitor the object reference instead of the actual content, after deep watching the object parameter, I can finally get the watch work! Thanks for all the help
<custom-dir para="{data: data}"></custom-dir>
Then in directive's link function
scope.$watch('para.data', function(n,o){
alert('changed')
}, true); //>> The true is important!!
The fact that you need to share scope is a bit weird knowing that you have a parent controller that can contain your $scope item
Pass the value to attribute in the <custom-dir> and <other-custom-dir>
<custom-dir data="data"> </custom-dir>
Observe the change from the directive
attrs.$observe('data', function(value){
// call your directive controller here ...
})
The Benefit :
By passing data from attribute, the directive do not have to know about the controller/the source of the data, so, this reduce dependecy.
It's considered a best practice to use "controllerAs" and no longer use $scope.
By writing:
<div ng-controller='ctrlA as a'>
<button ng-click='a.updateFactoryData(data)'></button>
<!-- ... -->
</div>
and:
function ctrlA () {
this.data = [];
this.updateFactoryData = function (data) {
//...
}
}
You access your controller's data with a.data everywhere inside your div.
Basically what you require is here is share the factory data changes in your directives. So you can bind your desired factory data using different approaches based on your requirements(i.e. # attribute,= 2 way model, & expression bindings) in directives and than watch those variables in directives link functions (i.e. ideal place where you needs to handle those watch conditions) for changes so once anything will update on factory (through button click), it will automatically propagated in your directives. Here is the example to do different bindings.
var myModule = angular.module('myModule', [])
.directive('myComponent', function () {
return {
restrict:'E',
scope:{
/* NOTE: Normally I would set my attributes and bindings
to be the same name but I wanted to delineate between
parent and isolated scope. */
isolatedAttributeFoo:'#attributeFoo',
isolatedBindingFoo:'=bindingFoo',
isolatedExpressionFoo:'&'
}
};
})
<my-component attribute-foo="{{foo}}" binding-foo="foo"
isolated-expression-foo="updateFoo(newFoo)" >
<h2>Attribute</h2>
<div>
<strong>set:</strong> <input ng-model="isolatedAttributeFoo">
<i>// This does not update the parent scope.</i>
</div>
<h2>Binding</h2>
<div>
<strong>get:</strong> {{isolatedBindingFoo}}
</div>
<h2>Expression</h2>
<div>
<input ng-model="isolatedFoo">
<button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">
Submit</button>
<i>// And this calls a function on the parent scope.</i>
</div>
</my-component>
I have made sample demo to illustrate the approach please check this.

ng-show nested in ng-repeat won't update

I've looked all over SO and Google and seen a whole bunch of reasons why ng-show wouldn't work inside of ng-repeat (scope issues, binding issues, etc.) but I can't quite pin down why mine isn't working. I was hoping that an extra pair of eyes could help me out. I'm very new to Angular, so hopefully my code makes some sense.
The goal: when $scope.current_set changes, the visible lmf-optionset changes. Currently, only the first optionset loads via Decision_Tree:loaded, and then when I try to load the next one via clickbox:clicked, $scope.current_set changes, but the view won't update.
JS
angular.module('lmf.option_set', [])
.controller('OptionsetCtrl', ['$scope', 'Optionsets', 'Decision_Tree',
function($scope, Optionsets, Decision_Tree) {
$scope.Optionsets = Optionsets;
$scope.current_set = {
name: null
};
$scope.$on('clickbox:clicked', function() {
$scope.current_set = Decision_Tree.get_next_optionset();
});
$scope.$on('Decision_Tree:loaded', function() {
$scope.current_set = Decision_Tree.get_next_optionset();
});
}
])
HTML
<div ng-controller='OptionsetCtrl'>
<div ng-repeat='set in Optionsets.option_sets'>
<div ng-show="set.name == current_set.name" lmf-optionset="{{set.name}}"></div>
</div>
</div>
Apparently lmf-optionset creates an isolated scope for each entry. These child scopes have link to parent's current_set, but they doesn't maintain a two-way binding. So when you are replacing the current_set value in you event handlers, child scopes are unaware that current_set was changed, and they are still referring to the old value.
You can either rewrite your event handlers like this:
$scope.current_set.name = Decision_Tree.get_next_optionset().name;
Or you can use controller as construction like this:
<div ng-controller='OptionsetCtrl as vm'>
<div ng-repeat='set in Optionsets.option_sets'>
<div ng-show="set.name == vm.current_set.name" lmf-optionset="{{set.name}}"></div>
</div>
</div>

AngularJS- How to call controller's function on click of checkbox which is created in directive template

I am new to angularJS. I want to create checkboxes dynamically using templates in directives. I created controller and directives in separate files. I am creating checkbox in template in directive and want to invoke controller's function on ng-click of check box but I am unable to do so.
Here is my code sample.
Controller:
var app=angular.module('abc',[]);
app.controller('DemoCtrl', function($scope) {
$scope.ctrlFn = function(test) {
alert("hi "+test);
console.log(test);
}
});
I referred the https://github.com/iVantage/angular-ivh-treeview to create checkboxes tree view. I inlcuded all the css and js files in my sample. From the link I got the following js file which is creating the checkboxes in template in directive as shown below:
ivh-treeview.min.js:
angular.module("ivh.treeview",[]),
angular.module("ivh.treeview").directive("ivhTreeviewCheckbox",[function(){
"use strict";
return{restrict:"A",
scope:{node:"=ivhTreeviewCheckbox"},
require:"^ivhTreeview",
link:function(a,b,c,d){
var e=a.node,f=d.opts(),g=f.indeterminateAttribute,h=f.selectedAttribute;
a.isSelected=e[h],
a.ctrl=d,
a.$watch(function(){return e[h]},function(b){a.isSelected=b}),
a.$watch(function(){return e[g]},function(a){b.find("input").prop("indeterminate",a)})},
template:['<input type="checkbox"','ng-model="isSelected"','ng-change="ctrl.select(node, isSelected)" />'].join("\n")}
}]);
View:
<div class="col-sm-8" ng-controller="DemoCtrl as demo">
<div ivh-treeview="demo.bag"
ivh-treeview-selected-attribute="'isSelected'"
ivh-treeview-id-attribute="'uuid'"
ivh-treeview-expand-to-depth="0">
</div>
</div>
I want to call ctrlFn() on click of checkbox created in directive template. Please suggest a way to do the same.
Thanks In Advance
Sounds like you are looking for a two-way binding between directive and parent $scope.
// parent controller scope
$scope.person = { name:'coldstar', class:'sexy beast' };
// directive declaration
<div a-person='person'></div>
// directive code
scope: {
// the = sign is the key. could also be a function instead of object
innerPerson: "=aPerson"
},
link: function (scope, elm, attr){
// now this change will be reflect in the parent controller also
scope.innerPerson.name = "not coldstar anymore";
}
Edit:
I also noticed "'isSelected'" which should be "isSelected" if isSelected is a $scope.* entity

How do I update my html on Click in Angularjs Controllers

I have the html Structure that I need to update from the json data. My Json data is in a Controller. I need to write an expression for ng-click event that will read the json data and put the in the corresponding div in html. but I am not sure how to acheive this.
Below is what I have so far.
<body data-ng-app>
<div class="container" data-ng-controller="UpdateDataCtrl">
<div class="inner1"></div>
<div class="inner2"></div>
</div>
UPdate Controllers
</body>
function UpdateDataCtrl($scope) {
$scope.data = [
{
"USA":"Eglish",
"Pop":"232423432432"
},
{
"France":"French",
"Pop":"1212323432"
},
{
"Spain":"Spainish",
"Pop":"3432432"
}
]
}
On each click the 2 Div should get updated from the json. First div should have USA---English Pop---2342234232 and then on next click the div should have data from France and so on.
http://jsfiddle.net/MBFpD/1/
Thanks
It appears that you are unclear on the concept of AngularjS. You don't want to update the DIVs. You want to reference your model and then change the data in your model.
For example you can write the div like this:
<div class="inner1">Population: {{data[dataindex].Pop}}</div>
Then in the Controller you initialize the dataindex to 0, so that this will output the population from the first entry in the array:
$scope.dataindex = 0;
The click function (you must have the link with the ng:click inside the block governed by the Controller!) could then just increase the dataindex by one and by using modulo restart at 0 again when the end of the array was reached.
$scope.click = function() {
$scope.dataindex = ($scope.dataindex+1) % $scope.data.length;
Here is an updated and modified jsfiddle of your example which will show everything in action: http://jsfiddle.net/MBFpD/2/
Bind your data to your scope when you click on the link:
$scope.update = function() {
$scope.data = data; //your array defined locally to the scope
};
ng-repeat your data bound to the scope; display the container if the size of the array is > 0.
Use {{index}} to get the iteration variable inside the loop.
Above all, move your ng-controller declarative at the top to enclose both your ng-repeat and your ng-click; otherwise, AngularJS cannot guess what you want to achieve.
http://jsfiddle.net/MBFpD/5/

Categories

Resources