I have written an angular directive that needs to update the parent scope.
angular.module('app').directive('googlePlace', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function ($scope, element, attributes, model) {
$scope.property1 = 'some val';
$scope.property2 = 'another val';
$scope.$apply();
};
});
But in my controller I do this:
MyCtrl = function($scope){
$scope.doSave = function(){
// do some logic
console.log($scope.property1);
console.log($scope.property2);
}
}
When doSave
runs, I'm getting undefined values in my console. How can I get it applied to the parents scope WITHOUT isolating the scope. I don't have this option because another directive on the same element isolates the scope.
It should work. By default if you don't specify scope in your directive it uses the parent scope so property1 and property2 should be set. try setting the scope in your directive to false. As a side note is not a good practice what you are doing. It will be better isolate the scope and add the property as attributes. This way you will have good encapsulation.
for example
angular.module('app').directive('googlePlace', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
property1: '=',
property2: '='
}
link: function ($scope, element, attributes, model) {
//here you have access to property 1 and 2
};
});
function MyCtrl($scope) {
$scope.property1 = null;
$scope.property2 = null;
$scope.doSave = function(){
// do some logic
console.log($scope.property1);
console.log($scope.property2);
}
}
And your html
<div ng-control="MyCtrl">
<div google-place property1='property1' property2='property2'></div>
</div>
I don't know what you are doing wrong, because it seems to work: http://jsfiddle.net/HB7LU/2865/
var myApp = angular.module('myApp',[]);
angular.module('myApp').directive('googlePlace', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function ($scope, element, attributes, model) {
$scope.property1 = 'some val';
$scope.property2 = 'another val';
$scope.$apply();
}
}
});
angular.module('myApp').controller('MyCtrl', MyCtrl);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.doSave = function(){
// do some logic
console.log($scope.property1);
console.log($scope.property2);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With