AngularJS Directive Two-Way Data Binding Not Working When Observing Boolean

后端 未结 2 1960
孤独总比滥情好
孤独总比滥情好 2020-12-06 16:27

I have a two-way data binding that is not altering the value of the variable sent to the directive.

My directive watches for a trigger and gives focus to the associa

相关标签:
2条回答
  • 2020-12-06 16:52

    Directive create a scope. when you pass parameter to scope, object passed by reference and boolean (and number, string...) passed by value.

    For example:

    function changeToFalse(bool) {
        bool= false;
        console.log(bool);  // false
    }
    
    
    function changeObjToFalse(obj) {
        obj.bool= false;
        console.log(obj.bool);  // false
    }
    
    var obj = {bool : true};
    
    changeToFalse(obj.bool);
    console.log(obj.bool);  // true
    changeObjToFalse(obj);
    console.log(obj.bool); // false
    

    See also same question - two way binding not working with ng-repeat.

    0 讨论(0)
  • 2020-12-06 17:05

    The problem you are experiencing is a common problem when dealing with primitive values (boolean, int, etc..) within scopes.

    I strongly suggest reading Understanding Scopes article. (short answer: primitives are changed in the directive's isolated scope, and are not seeked up the chain for the parent scope, i.e., your controller scope).

    As to how to solve your situation, I suggest to use dot notation and store your primitive inside an object, and bind this object to your directive:

    scope: {
       triggerObj: '=focusMe'
    },
    

    And make sure your trigger references in the directive are now scope.triggerObj.trigger.

    And in your controller have:

    $scope.triggerObj = {};
    $scope.triggerObj.trigger = true; //or false, what have you
    

    Having an object will make sure the two way binding will work. And read the article above when you have time :)

    0 讨论(0)
提交回复
热议问题