Angular Directive - create a new two-way binding and "navigate by value"

This is an extension of the previous question (and similar questions) in which I asked if it is possible to have an attribute in the directive to allow the transfer of such a value.

<my-directive att>                //Evaluates to true
<my-directive att="true">        
<my-directive att="false">
<my-directive att="51">
<my-directive att="51.234">
<my-directive att="'john smith'">  

or, can use two-way binding to a variable in an area like this.

<my-directive att="SomeVariableOnControllerScope"> 

Now this will not work with standard two-way binding "=". I tried various attempts, but whenever you try to change something inside your directive, it tries to write it back to a variable, and if it is not a corresponding variable, you get a standard error of "not assignable".

- , . , , , , float ​​ . , "" , . , = .

, , , , , . , HTML ( SEO), - . 2 .

, @ = , , .

?

+4
1
parse

1/$ ,

https://docs.angularjs.org/api/ng/service/ $parse

2/ , :

        var dataBind = function(parentScopeName, scopeName, childScope, parentScope) {
        if(parentScope == null) {
            parentScope = childScope.$parent;
        }
        var parentGet = $parse(parentScopeName);
        var compare = parentGet.literal ? angular.equals : function(a,b) { return a === b; };
        var lastValue;

        var parentSet = parentGet.assign || function() {
            // reset the change, or we will throw this exception on every $digest
            lastValue = childScope[scopeName] = parentGet(parentScope);
            throw "didnt understand this exception";
        };
        lastValue = childScope[scopeName] = parentGet(parentScope);
        return childScope.$watch(function parentValueWatch() {
            var parentValue = parentGet(parentScope);
            if (!compare(parentValue, childScope[scopeName])) {
                // we are out of sync and need to copy
                if (!compare(parentValue, lastValue)) {
                    // parent changed and it has precedence
                    childScope[scopeName] = parentValue;
                } else {
                    // if the parent can be assigned then do so
                    parentSet(parentScope, parentValue = childScope[scopeName]);
                }
            }
            return (lastValue = parentValue);
        }, null, parentGet.literal);
    }

, , , parse ( '=' '@'):

var parsed = $parse($attrs.myAttribute);
if(parsed.constant) {
     $scope.whereIWantMyConstantInChildScope = parsed();
} else {
     dataBind($attrs.myAttribute, "whereIWantMyConstantInChildScope", $scope); // 4rth param is optional, will fallback to parent scope.
}

.

, ( vs ) differents ( lazyness-driven- ) if/else . ...

+2

Source: https://habr.com/ru/post/1616726/


All Articles