angularjs指令隔离范围

时间:2014-03-18 09:25:17

标签: javascript angularjs

我有一个指令和一个控制器(主要是来自Angular JS Directives 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",为什么不评估"I'm a directive within the app Hello World"? 有人可以解释一下吗? 谢谢。

Plunker

1 个答案:

答案 0 :(得分: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>
相关问题