Isolate and shared scope same time in directive AngularJS - angularjs

New to Angular so not sure if I ask my question the right way.
So I have form.
<form ng-controller="myController" action="" method="get">
<div myDirective>
<input ng-model="question.sex" value="male" type="radio">
<input ng-model="question.sex" value="female" type="radio">
<button ng-click="log(LogThisQuestionAnsware())"></button>
</div>
<div myDirective>
<input ng-model="question.agree" value="no" type="radio">
<input ng-model="question.agree" value="yes" type="radio">\
<button ng-click="log(LogThisQuestionAnsware())"></button>
</div>
</form>
So my goal is to log current "question" answer. on button click.
How can I access local question in myDirective separate from my second directive and have in controller scope too.
--[ Edit: ]--
Ok this is pretty much my scenario. http://jsfiddle.net/y5esnm09/5
Each button have to log its own directive value not both radio values if they are selected.

If I correctly understood your question, you want both directive instances to bind to the same question object, but have their scopes separate from eachother:
Set up a two way data binding between your directive and your controller, e.g.:
<div my-directive question="question">
<!-- the rest -->
angular.module('your.module').directive('myDirective', function() {
return {
scope: question: '=',
//other props
}
This will ensure that both directives bind to the same question object but have their own separate scopes.
An alternative would be to set the scope property to true, that way they will both create a child scope of your controller.
EDIT: Fiddle demonstrating two way binding:
http://jsfiddle.net/L0eqf4qe/
PS: I converted myDirective to my-directive, angular will translate the snake-case to camelCase for you.

Related

Udating parent object from isolated scope in directive is not working at all

I have a directive defined like that:
myApp.directive('someDirective', function() {
return {
restrict: 'A',
scope: {
disableButton: '=',
},
templateUrl: 'sometemplate.html',
controller: 'SomeDirectiveController'
}
});
The controller for the directive looks as follows:
mLoan.controller('GiversDirectiveController', function (
$scope,
) {
$scope.checkGiversAmount = function () {
var giversCurrentTotalValue = $scope.stocksTotalAmount - $scope.giversCurrentAmount;
}
this is the directive view
<div class="row">
<div class="col-lg-2">
<label for="customer">Wybierz klienta</label>
<select id="customer"
name="customer"
class="form-control"
ng-model="selectedCustomerId"
ng-options="customer.Id as customer.Name for customer in customers"
ng-change="getGiversFunds(selectedCustomerId)"
required=""></select>
</div>
<div class="col-lg-2" ng-show="customerFunds.length > 0">
<label for="customerFunds">Wybierz fundusz</label>
<select id="customerFunds"
name="customerFunds"
class="form-control"
ng-model="selectedFundId"
ng-options="customerFund.Id as customerFund.Name for customerFund in customerFunds"
ng-blur="updateGiverFund(selectedCustomerId, selectedFundId)"
ng-required="customerFunds.length > 0"></select>
</div>
<div class="col-lg-2">
<label for="giversCurrentAmount">Ilość</label>
<input type="number" min="1"
max="{{giversCurrentAmount}}"
id="giversCurrentAmount"
name="giversCurrentAmount"
class="form-control"
ng-model="giversCurrentAmount"
ng-change="checkGiversAmount(selectedFundId)"
ng-blur="updateGiverStockAmount(selectedCustomerId, giversCurrentAmount)"
required />
</div>
<div class="col-lg-2">
<label for="commission">FEE%</label>
<input type="number"
min="1"
id="commission"
name="commission"
class="form-control"
ng-model="commission"
ng-blur="updateGiverCommission(selectedCustomerId, commission)"
required />
</div>
<div class="col-lg-4">
<label for="minimalCommission">FEE Min</label>
<input type="number"
min="1"
id="minimalCommission"
name="minimalCommission"
class="form-control"
ng-model="minimalCommission"
ng-blur="updateGiverMinimalCommission(selectedCustomerId, minimalCommission)"
required />
</div>
</div>
And a parent view where I'm Using the directive with the button:
<div ng-repeat="giver in givers">
<div givers-directive givers="givers"
givers-current-amount="giversCurrentAmount"
disable-giver-side-add="parent"
stocks-total-amount="stocksTotalAmount">
</div>
</div>
<div class="row">
<div class="col-lg-12 margin-top-10px">
<button id="addGiverSide"
name="saveLoan"
class="btn btn-primary"
ng-click="addGiverSide(AddLoansForm)"
ng-disabled="disableButton">
Dodaj
</button>
</div>
</div>
Now my problem and question ath the same time is how I can update the disableButton from the parent model. Before you say this is a duplicate I've ran through the solutions taht was on stackoverflow mainly this one: How to access parent scope from within a custom directive *with own scope* in AngularJS? and that one: What are the nuances of scope prototypal / prototypical inheritance in AngularJS? but nothing seems to help. What is straneg (or not) I can't use the $parent to get to that. I have to go through: $scope.$parent.$parent path and then it's getting updated. Besides that it looks ugly and strange, it's not working when I'm trying to updated this variable from the parent view. To sum up one effect is working and the other is not. And after changing is the other way around. I've tried to wrap up the disable button into an object and try to do the change but this does not work also. Or maybe I'm doing it wrong. Please kindly help me because I'm running out of ideas. What am I doing wrong?
UPDATE
I'm adding the rest of the directive view to show the concept what I'm trying to achieve here. THere are drop downs wich I want them to be independent. Because without the directive with separated (or isolated) scope the two dropdowns are getting filled by changing the other. I want to change them indepenently. I've managed to achieve thet through out the isolated scope. But now I can't seem to get the disabling button working.
By defining a scope inside your directive, you lock your directive out of the parent's scope. If you want to make use of a parent scope, you should set your scope to true.
You can read more on the matter here: http://www.sitepoint.com/practical-guide-angularjs-directives/
EDIT: Example
myApp.directive('someDirective', function() {
return {
restrict: 'A',
scope: true,
templateUrl: 'sometemplate.html',
controller: 'SomeDirectiveController'
}

How we set to ng-model variable to parent controller in nested controllers scope

I have one ng-controller nested in another controllers scope.
I want to set scope variable in nested controller scope, to parent controller.
I have view:
<div ng-controller="MyCtrl">
<input type="text" ng-model="name"/>
<div ng-controller="CountryDataController">
<angucomplete
(...)
selectedObject="country"/>
</div>
</div>
which is part of the form.
Then on form submit i want to send ng-models from MyCtrl ( name,country) doing:
fields: {name: $scope.name,
country: $scope.country,
},
How can i tell angular, that selectedObject model belongs to MyCtrl, and not CountryDataController.
I tried
selectedObject="MyCtrl.country"
selectedObject="country[MyCtrl]"
but without effects.
selectedObject in angucomplete works like ng-model.
Also I don't want to rewrite logic from CountryDataController to MyCtrl, because in first i have fields for autocomplete and in second file uploading.
Is there any convention for this?
The answer is:
selectedobject="$parent.country"
You can use $parent, but if you move your HTML or eventually add another controller it between it will break.
The correct way to do that is to use the controller as syntax, as shown below:
<!-- use topCtrl to access this controller scope -->
<div ng-controller="MyCtrl as topCtrl">
<input type="text" ng-model="name"/>
<!-- use countryCtrl to access this controller scope -->
<div ng-controller="CountryDataController as countryCtrl">
<angucomplete
(...)
selectedObject="topCtrl.country"/>
</div>
</div>

AngularJs - model value does not reflect on ui in nested controllers case

I am using angularjs for one of the my module in application. I want to update UI of various locations on page, so that all ui components will work synchronously as the model value changes.
here is my html-
<fieldset ng-controller="controller1" >
<legend>Divs with common controller</legend>
<div style="background-color:#eee;padding:3px;">
<input type="text" ng-model="Model1" />
</div>
<div style="background-color:#eee;padding:3px;">
<input type="text" ng-model="Model1" />
</div>
</fieldset>
<fieldset ng-controller="controller1" >
<legend>Divs with common controller</legend>
<div style="background-color:#eee;padding:3px;" ng-controller="controller2">
<input type="text" ng-model="Model1" />
<input type="text" ng-model="Model2" />
</div>
<div style="background-color:#eee;padding:3px;">
<input type="text" ng-model="Model1" />
</div>
</fieldset>
and my javascript -
var testApp = angular.module('testApp',[]);
var mainApp = angular.module('mainApp',['testApp']);
testApp.controller("controller1",['$scope',function($scope){
$scope.Model1 = "testText";
}]);
testApp.controller("controller2",['$scope',function($scope){
$scope.Model2 = "testText2";
}]);
angular.bootstrap(document, ['mainApp']);
In the html for first fieldset it is working properly. But in second fieldset it is not. So can anyone please tell me how do i achieve the functionality of first fieldset in second fieldset.
Thanks.
use $rootScope instead of $scope
Can you use ng-controller="controller2" to particular input.
Try this
<div style="background-color:#eee;padding:3px;">
<input type="text" ng-model="Model1" />
<input type="text" ng-model="Model2" ng-controller="controller2" />
</div>
It doesn't work because you create 2 seperate scopes/instances for controller1
<div>
// Root scope
<div ng-controller="controller1">
// Child scope A
// scope = new controller1();
</div>
<div ng-controller="controller1">
// Child scope B
// scope = new controller1();
</div>
</div>
You can solve this problem by using the $rootScope directly or by creating a service. The recommended way is to avoid $rootScope whenever possible and use a service instead.
Value is probably the easiest way to create a service. Note that you can also use .service or .factory. Read more in the documentation about services.
testApp.value('myValue', {
data: 'testText'
});
I'm using an object here so we can use this as a reference to the value, this is important for sharing data between controllers. If you want to know why then read more about reference & value types.
Now inject this service into your controller and use this data instead:
testApp.controller("controller1",['$scope', 'myValue',function($scope, myValue){
$scope.Model1 = myValue;
}]);
On the view we need to update the bindings to the reference of the service:
<input type="text" ng-model="Model1.data" />
JSFIDDLE
USE THE DOT! ng-model without "." is bad.
Please read this
What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
The issue is fully described there.

AngularJs multiple instances and nested controller

I got confused a bit about whether can we create multiple instance of controller and that to in nested form for eg -
<div ng-controller="abc">
<form ng-submit="call()">
<input type=text ng-model="content"/>
</form>
<div ng-controller = "abc">
<form ng-submit="call()">
<input type=text ng-model="content"/>
</form>
</div>
</div>
i just want to know that if i use the same model with other instance of controller, so model value would be same or different. Similar to static variable ?
i just want to know that if i use the same model with other instance
of controller, so model value would be same or different. Similar to
static variable ?
All declarations of ng-controller create a new instance of the controller. So, if you had two instances side by side, like this:
<div ng-controller="abc">
<input type=text ng-model="content"/>
</div>
<div ng-controller="abc">
<input type=text ng-model="content"/>
</div>
plunker
then, all of the $scope properties of each would be completely independent.
When a ng-controller is nested, then its scope inherits the parent controller's scope. So for this you'd expect that content refers to the same scope property:
<div ng-controller="abc">
<input type=text ng-model="content"/>
<div ng-controller="abc">
<input type=text ng-model="content"/>
</div>
</div>
plunker
However, since content is not defined directly in the controller something strange happens. If you fill in the parent input first. Both, inputs become bound to the same scope property. However, if you fill in the child input first, they are independent!
This can be confusing until you understand that Angular is being lazy when it creates the property on the scope. content is null at first on both scopes. It is only when it has a value that it will inherit.
So, what do you do if you want to keep things separate? Add an initial value to a $scope property inside the controller:
app.controller('abc', function($scope) {
$scope.content = '';
});
plunker
This way, each separate controller instance is initialized with its own content property.
Hope this helps.

How to prevent transcluding directive to create new child scope for the form directive?

I have a problem with directive transclude and the form directive. As you may know, the form will end up in the "scope" if you add the "name"-property to the form tag, then you can check for form validation and so on.
My problem start when i put the form tag in a directive that uses transclude. I'm aware of how to deal with this problem with two-way data binding, as mention here https://stackoverflow.com/a/14484903/1029874 -- "use an object instead of a primitive"
But my form ends up in the transcluding directives scope. Here is an example of what i want to do.
<div ng-controller="appCtrl">
<widget>
<widget-header>{{model.property}}</widget-header>
<widget-body>
<!-- The form will end up in "widget-body":s scope instead of appCtrl:s scope -->
<form name="appForm" ng-submit="submit()">
<input type="text" required ng-model="model.property" />
<input type="submit" value="submit" />
</form>
</widget-body>
</widget>
</div>
And here is the fiddle, http://jsfiddle.net/WLksJ/1/
Is there a way that I can get around this behavior?
Thanks!
An interesting question, but a problem that's easily avoided by using
<form name="appForm" ng-submit="submit(appForm.$valid)">
and checking the parameter in the submit function.
http://jsfiddle.net/udMJ7/
Another (perhaps better) option is to use this which is set to the scope of the last controller (in this case the form controller, which we want)
$scope.submit = function(){
if(this.appForm.$valid){
//post the form!!
}
};
http://jsfiddle.net/udMJ7/1/

Resources