父范围更改

时间:2017-03-30 21:37:52

标签: angularjs directive

当我通过从指令调用函数来更新自定义指令中的父作用域变量时,指令dom不会更新。 在此示例中,$ scope.ascending为true,sort()函数执行切换其值。我从父视图和子视图(指令)调用sort函数,但更改不会反映在指令模板中。按原样运行此代码以查看问题

HTML

<html ng-app="sortApp">
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
        <script src="testApp.js"></script>
    </head>
    <body>
        <div ng-view>
            <div ng-controller="sortController">
                <span>Parent scope: sorting order: </span>"{{ascending ? 'a->z' : 'z->a'}}"
                <br /><br />
                <div><input type='button' value='toggal sort order from parent' ng-click='sort()' /></div><br/>
                <sorting-from-directive asc="ascending" sort-action="sort()"> </sorting-from-directive>
            </div>
        </div>
    </body>
</html>

CODE

var app = angular.module('sortApp', []);

app.controller('sortController', function ($scope) {

    $scope.ascending = true;

    $scope.sort = function () {

        $scope.ascending = !$scope.ascending;
    }

});

app.directive('sortingFromDirective', function () {

    return {
        restrict: 'EA',
        scope: {
            asc: '=',
            sortAction: '&'
        },
        template: "<div><input type='button' value='toggal sort order from directive' ng-click='sortAction()'/> <span>Child scope: sorting order:</span><span ng-show={{asc}}>a->z</span> <span ng-hide={{asc}}>z->a</span></div>"
    };
});

1 个答案:

答案 0 :(得分:0)

你不应该在{{}} / ng-show

内使用ng-hide(插值)
<span ng-show='asc'>a->z</span> 
<span ng-hide='asc'>z->a</span>