Reputation: 89
I'm trying to create a dynamic directive that will receive his binding options from attributes. This is my controller view:
<div ng-controller="OtCtrl">
<div ng-include src="'/client/views/openTradeView.html'"></div>
</div>
my View:
<div>
{{name}}
<div swings binding="Risk" title="Risk"></div>
<div swings binding="Amount" title="Amount"></div>
</div>
This is my directive View:
<div>
{{title}}
<a href="javascript:void(0)" ng-click="minus()">-</a>
{{amount}}
<a href="javascript:void(0)" ng-click="plus()">+</a>
</div>
This is my directive:
app.directive("swings", function () {
return {
replace: true,
scope: {
title : '@title',
amount: '=binding',
extra: '=bindingExtra'
},
resctrict: "A",
controller: function($scope){
$scope.minus = function (event, binding) {
$scope.amount -= 1;
console.log(binding)
}
$scope.plus = function (event) {
$scope.amount += 1;
}
},
templateUrl: '/client/views/swingsDirectiveView.html'
}
});
And finally my Controller:
app.controller("OtCtrl", ['$scope', function ($scope) {
$scope.Amount = 400;
$scope.Risk = 100;
setInterval(function(){
console.log($scope.Risk)
},2000);
}]);
I know that when I use ng-view, angularjs creates new scope. My issue that when I click plus or minus, the amount in the directive updates but the Risk model in the controller not, but on first load directive takes the risk init value and set the amount.
How can I fix this issue.
Thanks
Upvotes: 2
Views: 1669
Reputation: 4329
I would suggest creating a model
property in your controller like so:
app.controller("OtCtrl", ['$scope', function($scope) {
$scope.model = {
Amount: 400,
Risk: 100
}
}]);
Then, bind it to your directive via:
<div swings binding="model.Risk" title="model.Risk"></div>
What is likely happening is that scope inheritance is creating a copy of Amount
and Risk
(since they're primitives); whereas creating an object like this causes the reference to get copied, meaning the scope hierarchy shares the same data.
Upvotes: 1