Angularjs指令隔离作用域

angularjs directive isolated scope

本文关键字:作用域 隔离 指令 Angularjs      更新时间:2023-09-26

我有一个指令和一个控制器根据这(它来自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"而不是"I'm a directive within the app Hello World" ?有人能解释一下吗?谢谢你。

恰好

原因是,您必须输入模板内部指令的template属性,使其成为孤立的一个。现在,指令创建了一个孤立的作用域,但它不会在任何地方使用它,因为当指令的link函数被触发时,指令标签中的内容已经在父作用域(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>