AngularJS: Include and scope inheritance = broken bindings?

后端 未结 2 1420
遇见更好的自我
遇见更好的自我 2021-01-07 04:03

In an attempt to clean up my partials I recently moved some of my global menus into seperate templates which I now include in the views which need them. As the menu (includi

相关标签:
2条回答
  • 2021-01-07 04:45

    Try using $parent instead of $scope in your included template

    0 讨论(0)
  • 2021-01-07 05:01

    As discussed in the comments above, ng-include creates a new child scope. So in your searchBarTemplate, using ng-model="searchBar" results in a new searchBar property being created on the child scope, which hides/shadows the parent searchBar property of the same name.

    In the controller, define an object:

    $scope.obj = {searchBar: 'Hello World!};
    

    And then use

    ng-model="obj.searchBar" 
    

    in your template. When objects are used (instead of primitives), the child scope does not create a new property. Rather, due to the way JavaScript prototypal inheritance works, the child scope will find the property on the parent scope.

    See also https://stackoverflow.com/a/14146317/215945 which has a picture showing the child and parent scopes and how the child property hides/shadows the parent property if a primitive is used.

    Note that using $parent is another option, but it is not "best practice".

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