Access $scope variable inside directive template and update controller $scope.variable - angularjs

I have create a simple directive with an input element and span. Using the directive I created two custom elements with isolate scope. Now, I am trying to get the sum of the data entered in the input element of the directive. But really can't figure out how to do that.
Here is the my controller and directive :
angular.module('mapp',[])
.controller('ctrl',['$scope',function($scope){
$scope.total = 0;
}])
.directive('customElement',function(){
return {
restrict: 'E',
scope:{
data: '=info'
},
template: '<input type="text" ng-model="data1">\
<span>{{data1}}</span>'
}
});
I'm looking to sum up data1 of all directives elements and update $scope.total. Here is the HTML code:
<div ng-app="mapp">
<div ng-controller="ctrl">
<custom-element info="a"></custom-element>
<custom-element info="b"></custom-element>
<br/>
<br/> Total: <span>{{total}}</span>
</div>
</div>
Here is a DEMO

Here is a working fiddle
angular.module('mapp', [])
.controller('ctrl', ['$scope', function ($scope) {
$scope.total = 0;
$scope.a = 0;
$scope.b = 0;
$scope.$watchCollection('[a,b]', function () {
console.log('watch');
$scope.total = $scope.a + $scope.b;
});
}])
.directive('customElement', function () {
return {
restrict: 'E',
scope: {
data: '=info'
},
template: '<input type="number" ng-model="data">\
<span>{{data}}</span>'
}
});
A version without $watch
A version with ng-repeat

Total: <span>{{a+b}}</span> this would also work in the html without using a $watch or function from the controller

Here is you can do with $watch
Controller
.controller('ctrl',['$scope',function($scope){
$scope.test = {};
$scope.test.a = 0;
$scope.test.b = 0;
$scope.$watch('test',function(newVal,oldVal){
$scope.total = $scope.test.a + $scope.test.b
},true)
$scope.total = 0;
}])
Directive change ng-model="data1" to ng-model="data"
template: '<input type="number" ng-model="data">\
<span>{{data}}</span>'
Working Fiddle

Related

Generate HTML in custom directive and $compile in AngularJS

PLUNKER:
https://plnkr.co/edit/IQpGhinzsHUUqmwbHFmQ?p=preview
I am trying to create a form that reads from some JSON and creates the relevant view. Each set of questions are in their own step. I am having trouble getting access to each input to validate it using AngularJS.
How do I get access to the answers model that is created in the forEach loop?
HTML:
<form ng-app="MyApp" novalidate >
<section class="question step " ng-controller="StepController">
<div class="step-contents">
{{title}}
<step-contents content="content" ></step-contents>
</div>
<button >Prev</button>
<button ng-click="nextStep(content)">Next</button>
</section>
</form>
My AngularJS:
var app = angular.module('MyApp', []);
app.controller('StepController', function($scope) {
$scope.index = 0;
$scope.nextStep = function() {
console.log($scope.answers); // This should be the input data for _THIS_ step only
}
$scope.showStep = function() {
//FOREACH HAPPENS HERE
// Loops over some JSON to generate the following HTML:
$scope.title = "Step 1 title";
var html = '<input type="number" ng-model="answers.amount" />';
html += '<input type="text" ng-model="answers.name" />';
$scope.content = html;
//FOREACH ENDS HERE
}
$scope.showStep();
});
app.directive('stepContents', function ($compile) {
var linker = function(scope, element, attrs){
element.html(scope.content);
$compile(element.contents())(scope);
};
return {
restrict: 'E',
link: linker,
scope: {
content: '=',
},
};
});
Give a name to your form, and then you can access the form elements with $scope.formName.inputName, which will reference the ngModelController of the input. Check out Angular's documentation for ngFormController and ngModelController for more details.

Angularjs 2-way data binding push object from directive to controller array

I have a array defined in controller and passing it to directive using two way binding. In directive, i tried to pushed object into that array but it failed.
.controller("test", function($scope){
$scope.myarr =[];
$scope.$watch("myarr", function(newValue, oldValue){
console.log($scope.myarr); //prints empty arr
},true);
});
.directive('ptest', ['$compile', function($compile) {
var object = {value: 'changed value'};
return {
restrict:"E"
scope: {
myarr:"="
},
template : "<div>{{iobj.value}}<div>",
link: function(scope,elem,attr){
myarr.push(object) ;
}
};
}]);
html
<ptest myarr="myarr"></ptest>
Try scope.myarr.push(object); instead of myarr.push(object)
as #George Lee said try scope.myarr.push(object); and also your directive have a mistake. after restrict:"E" you forgot put ,
return {
restrict:"E", // forgot put ','
scope: {
myarr:"="
},
template : "<div>{{iobj.value}}<div>",
// Code goes here
angular.module('app', [])
.controller("test", function($scope){
$scope.myarr =[];
$scope.$watch("myarr", function(newValue, oldValue){
console.log($scope.myarr); //prints empty arr
},true);
$scope.addItem = function(){
var object = {value: 'changed value2'};
$scope.myarr.push(object);
}
})
.directive('ptest', ['$compile', function($compile) {
var object = {value: 'changed value'};
return {
restrict:"E",
scope: {
myarr:"="
},
template : '<div ng-repeat="item in myarr">{{item.value}}<div>',
link: function(scope,elem,attr){
scope.myarr.push(object) ;
}
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="test">
<ptest myarr="myarr"></ptest>
<input type="button" ng-click="addItem()" value="add">
</div>

Angular $watch not working on controller variable updated by directive

I am trying to place a watch on controller variable which gets updated from a directive using function mapping. variable is getting updated and logged in console but watch on it not working.
Code Snippet :
index.html
<body ng-app="myApp" ng-controller="myCtrl">
<div>
<test on-click="update()"></test>
</div>
app.js
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope){
$scope.test = {
value: false
};
$scope.update = function() {
$scope.test.value = !$scope.test.value;
console.log("Update: " + $scope.test.value);
};
$scope.$watch('test', function(newVal){
console.log("Watch: " + newVal.value);
}, true);
});
myApp.directive('test', function($compile){
return {
restrict: 'E',
transclude: true,
replace: true,
scope: {
onClick: '&'
},
template: '<div ng-transclude=""></div>',
link: function(scope, element, attrs) {
var $buttonElem = $('<button>Test</button>').appendTo(element);
$buttonElem.click(function(){
scope.onClick();
});
}
}
});
Plunker Link is : https://plnkr.co/edit/41WVLTNCE8GdoCdHHuFO?p=preview
The problem is that the directive is raising the event using code that is not apart of AngularJS instead of using an ng-click in its template. If you can't modify the directive, then wrap your event handler in $scope.$apply instead.
$scope.update = function() {
$scope.$apply(function(){
$scope.test.value = !$scope.test.value;
console.log("Update: " + $scope.test.value);
});
};

How to access ng-model value in directive?

I created a directive for google map auto-complete. everything is working fine, but the problem is when I need to access the value of input and re-set it. it doesn't work. Here is code:
<div controller='mainCtr'>
<span click='reset(destination)'>Reset</span>
<div class='floatleft' style='width:30%;margin-right:40px;'>
<smart-Googlemaps locationgoogle='destination.From'></smart-Googlemaps>
<label>From</label>
</div>
</div>
In the directive:
angular.module('ecom').directive('smartGooglemaps', function() {
return {
restrict:'E',
replace:false,
// transclude:true,
scope: {
locationgoogle: '='
},
templateUrl: 'components/directives/autocomplete/googlemap-search.html',
link: function($scope, elm, attrs){
var autocomplete = new google.maps.places.Autocomplete($(elm).find("#google_places_ac")[0], {});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
// $scope.location = place.geometry.location.lat() + ',' + place.geometry.location.lng();
// console.log(place);
$scope.locationgoogle = {};
$scope.locationgoogle.formatted_address = place.formatted_address;
$scope.locationgoogle.loglat = place.geometry.location;
$scope.locationgoogle.locationText = $scope.locationText;
$scope.$apply();
});
}
}
})
Here is html for directive:
<input id="google_places_ac" placeholder="Please enter a location" name="google_places_ac" type="text" class="input-block-level" ng-model='locationText'/>
The directive works fine, I create a isolated scope(locationgoogle) to pass the information I need to parent controller(mainCtr), now in the mainCtr I have a function calld reset(), after I click this,I need to clean up the input make it empty. How Can I do it?
One way to access the value of the model in your directive from a parent controller is to put that on the isolate scope too and use the two-way binding flag = like you've done with the locationgoogle property. Try this:
DEMO
html
<body ng-controller="MainCtrl">
<button ng-click="reset()">Reset</button>
<smart-googlemaps location-text="locationText"></smart-googlemaps>
</body>
js
app.controller('MainCtrl', function($scope) {
// need to define model in parent and pass to directive
$scope.locationText = {
value: ''
};
$scope.reset = function(){
$scope.locationText.value = '';
}
});
app.directive('smartGooglemaps', function() {
return {
restrict:'E',
replace:false,
// transclude:true,
scope: {
locationgoogle: '=',
locationText: '='
},
// ng-model="locationText.value"
template: '<input id="google_places_ac" placeholder="Please enter a location" name="google_places_ac" type="text" class="input-block-level" ng-model="locationText.value"/>',
link: function($scope, elm, attrs){
// implement directive googlemaps logic, set text value etc.
$scope.locationText.value = 'foo';
}
}
})

AngularJS - set a model defined in a directives template

I have a directive defined like so:
angular.module('directives.myInput', [])
.directive('myInput', function($parse, $http, $sce){
return {
restrict: 'E',
template: '<input type="text" ng-model="searchStr" />',
controller: function($scope){
$scope.keyPressed = function(event){
$scope.showDropdown = true;
.
.
.
}
}
};
});
And then I have a button in html and directive above declared like so:
<div ng-controller="IndexCtrl">
<button ng-click="startNewLog()">Start</button>
<div ng-controller="ItemNewCtrl">
<myInput />
</div>
</div>
I want to change/initialize ng-model="searchStr" model on a button ng-click. How can I do that?
Thanks guys,
Jani
If I understand you right, first of all you need call child controller with $broadcast. Since we don't use isolate scope, we just call directive method from child controller:
[Short answer]
No isolate scope example
Demo 1 Fiddle
For isolate scope, I would map value to directive that listens on value change automatically:
Isolate scope example
Demo 2 Fiddle
[Full answer]
No isolate scope example
HTML
<div ng-controller = "IndexCtrl">
<button ng-click="startNewLog()">Start</button>
<div ng-controller="ItemNewCtrl">
<my-input></my-input>
</div>
</div>
JS
var app = angular.module('myModule', []);
app.controller('IndexCtrl', function ($scope) {
$scope.startNewLog = function(){
$scope.$broadcast('someEvent');
};
});
app.controller('ItemNewCtrl', function ($scope) {
$scope.$on('someEvent', function() {
$scope.callDirective();
});
});
app.$inject = ['$scope'];
app.directive('myInput', function(){
return {
restrict: 'E',
template: '<input type="text" ng-model="searchStr" />',
controller: function($scope){
$scope.searchStr;
$scope.keyPressed = function(event){
$scope.showDropdown = true;
}
},
link: function(scope, elm, attrs) {
scope.callDirective = function() {
scope.searchStr = 'callDirective';
};
}
};
});
Isolate scope example
HTML
<div ng-controller = "IndexCtrl">
<button ng-click="startNewLog()">Start</button>
<div ng-controller="ItemNewCtrl">
<my-input my-model='contInput'></my-input>
</div>
</div>
JS
var app = angular.module('myModule', []);
app.controller('IndexCtrl', function ($scope) {
$scope.startNewLog = function(){
$scope.$broadcast('someEvent');
};
});
app.controller('ItemNewCtrl', function ($scope) {
$scope.contInput = '';
$scope.count = 0;
$scope.$on('someEvent', function() {
$scope.contInput = 'hey mate';
});
});
app.$inject = ['$scope'];
app.directive('myInput', function(){
return {
restrict: 'E',
scope:{searchStr: '=myModel'},
template: '<input type="text" ng-model="searchStr" />',
controller: function($scope){
$scope.searchStr;
$scope.keyPressed = function(event){
$scope.showDropdown = true;
}
}
};
});

Resources