Nested object inside scope object in user directive

Why I don’t have a snap in a nested object in an object of my scope:

app.directive('myDirective', function() {
    return {
        scope: {
            dropdown: {
                option: '=selectedOption' //not working
            } 
        }
    }
})

I get an error message:

a.match is not a function

Here is the working plunker.

+4
source share
2 answers

The answer to “why” is “because that’s not how it works.”

The source code of AngularJS, which analyzes the scope of the directive, is here: https://github.com/angular/angular.js/blob/master/src/ng/compile.js#L829

  function parseIsolateBindings(scope, directiveName, isController) {
    var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;

    var bindings = {};

    forEach(scope, function(definition, scopeName) {
      var match = definition.match(LOCAL_REGEXP);

      if (!match) {
        throw $compileMinErr('iscp',
            "Invalid {3} for directive '{0}'." +
            " Definition: {... {1}: '{2}' ...}",
            directiveName, scopeName, definition,
            (isController ? "controller bindings definition" :
            "isolate scope definition"));
      }

      bindings[scopeName] = {
        mode: match[1][0],
        collection: match[2] === '*',
        optional: match[3] === '?',
        attrName: match[4] || scopeName
      };
    });

    return bindings;
  }

, scope .

+1

, :

scope: {
    "dropdown.option": "=selectedOption"
}

, , :

app.directive('myDirective', function() {
    return {
        scope: {
            dropdownOption: "=selectedOption"
        },
        controller: ["$scope", function($scope) {
            $scope.dropdown = $scope.dropdown || {};

            $scope.$watch('dropdownOption', function(newValue) {
                $scope.dropdown.option = newValue;
            });


            $scope.$watch('dropdown.option', function(newValue) {
                $scope.dropdownOption = newValue;
            });
        }]
    }
})
0

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


All Articles