2

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

1
  • I'm not sure that I understand your question. I created a Plunker with your code and it seems to work okay, but maybe you can re-word your question. There must be something I'm missing. Here's the Plunk: plnkr.co/edit/9OXRGJ?p=preview Commented May 1, 2013 at 16:04

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.