AngularJS指令隔离作用域

4

我有一个指令和一个控制器,根据这个(主要来自Angular JS指令PacktPub书)。

angular.module('myApp',[])
.directive('myIsolatedScopedDirective', function(){
    return {
        scope : {
            'title' : '@msdTitle'
        },
        link: function ($scope, $element, $attrs) {
            $scope.setDirectiveTitle = function (title) {
                $scope.title = title;
            };
        }
    };
})
.controller('MyCtrl', function($scope){
    $scope.title = "Hello World";
    $scope.setAppTitle = function(title){
      $scope.title = title;
    };
});


<div ng-controller="MyCtrl">
    <h2>{{title}}</h2>
    <button ng-click="setAppTitle('App 2.0')">Upgrade me!</button>
    <div my-isolated-scoped-directive msd-title="I'm a directive within the app {{title}}">
        <h4>{{title}}</h4>
        <button ng-click="setDirectiveTitle('bob')">Bob it!</button>
    </div>
</div>

问题如下: 为什么<h4>{{title}}</h4>的结果是"Hello World",而不是"我是在应用程序 Hello World 中的指令"? 请问有人能解释一下吗? 谢谢。

Plunker

1个回答

5

原因是,您必须在指令的template属性中输入模板,以使其成为隔离作用域。目前,该指令创建了一个隔离作用域,但它没有在任何地方使用它,因为在触发指令的链接函数时,您指定的指令标签内的内容已经在(MyCtrl)父级作用域中评估完毕。

这可能是您想要做的: http://plnkr.co/edit/jmWrNpLFttDPhSooPF0M?p=preview

指令

.directive('myIsolatedScopedDirective', function(){
    return {
        scope : {
            'title' : '@msdTitle'
        },
        replace: true,
        template: '<div><h4>{{title}}</h4>' +
          '<button ng-click="setDirectiveTitle(\'bob\')">Bob it!</button>',
        link: function ($scope, $element, $attrs) {
            $scope.setDirectiveTitle = function (title) {
                $scope.title = title;
            };
        }
    };

标记语言

<div my-isolated-scoped-directive msd-title="I'm a directive within the app {{title}}"></div>

谢谢。那我认为那本书是一坨垃圾...所以没有办法将指令“content”/innerHTML(不是从模板生成的那个!)绑定到指令的隔离作用域中?也许可以用 transclude? - pr0da
我没有尝试过那个,但是转置可能也可以完成这项工作。 - doodeec

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接