2

为了清理我的部分内容,我最近将一些全局菜单移到了单独的模板中,现在我将这些模板包含在需要它们的视图中。由于菜单(包括搜索栏)是全局的,我创建了一个服务来跟踪菜单的状态等。

问题是在我开始包含之后发生了一些有趣的事情。

视图的 HTML (Jade)

div(ng-controller='HeroUnitCtrl', ng-include src='heroTemplate')
div(ng-controller='MainSearchBarCtrl', ng-include src='searchBarTemplate')

div.row-fluid
    div.span12
        table.table.table-striped.table-bordered
            tr
                th
                    a(ng-click='setOrder("id")') ID#
                th
                    a(ng-click='setOrder("client.name")') Kunde
                th
                    a(ng-click='setOrder("technician.name")') Tekniker
                th
                    a(ng-click='setOrder("createdAt")') Opprettet
                th
                    a(ng-click='setOrder("statusString")') Status

            tr(ng-repeat='record in records | orderBy:orderProp | filter:searchBar')
                td
                    a(ng-href='#/records/show/{{record.id}}') {{record.id}}
                td {{record.client.name}}
                td {{record.technician.name}}
                td {{record.createdAt}}
                td {{record.statusString}}

HTML (Jade) 搜索栏模板

input#searchField.input-xxlarge(type='text', placeholder='placeholder', ng-change='searchBarUpdated()', ng-model='searchBar')

到现在有点看不懂了

MainSearchBarCtrl

function MainSearchBarCtrl(MainSearchBarService, $scope, $location) {
    $scope.searchBarTemplate = 'partials/main-searchbar';
    $scope.searchBar = 'Hello World!';

    $scope.searchBarUpdated = function() {
        console.log('Search bar update: ' + $scope.searchBar);
        MainSearchBarService.searchBarUpdated($scope.searchBar);
    }   
}

最初,searchBar的值与预期的一样是“Hello World”。但是,如果我附加任何文本,它仍然只打印“Hello World”。或者,如果我替换它打印未定义的文本。所以看起来绑定被打破了,但我真的不明白为什么会这样。值得一提的是,在我将搜索栏移到单独的模板中之前,情况并非如此。

任何帮助是极大的赞赏。

4

2 回答 2

9

正如上面评论中所讨论的,ng-include创建一个新的子范围。因此,在您的 searchBarTemplate 中,使用ng-model="searchBar"结果会在子范围内创建一个新searchBar属性,该属性会隐藏/隐藏searchBar同名的父属性。

在控制器中,定义一个对象:

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

然后使用

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".

于 2013-03-29T15:41:35.583 回答
0

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

于 2013-03-29T17:30:19.540 回答