为什么我不能够访问正确的范围是什么? [英] Why I can't access the right scope?

查看:90
本文介绍了为什么我不能够访问正确的范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML

<!doctype html>
<html>
<head>
</head>
<body>
<div ng-app="project">
   <div ng-controller="mainCtrl">
    {{ property1 }}
    <br />
    {{ property2 }}
    <div class="ts" d-child property1="{{ property1 }}cloud" property2="property2">
        property1: {{ property1 }}
        <br />
        property2: {{ property2 }}
    </div>

    </div>
    </div>
    </body>
</html>

JS:

angular.module('project', [])
.controller('mainCtrl', function($scope) {
    $scope.property1 = 'ss';
    $scope.property2 = 'dd';
});

angular.module('project')
.directive('dChild', function() {
    return {
        restrict: 'A',
        scope: {
            property1: '@',
            property2: '='
        },
        link: function(scope, element, attrs) {

        }
//      template: '<input type="text" ng-model="property1" />'
    }
})

我想到了 property1:{{property1}} 将是property1:sscloud,但它原来是SS,仿佛它仍然指向在 mainCtrl 控制器的范围,应该不会是指在 D-子指令的范围有多大?

I thought the property1: {{ property1 }} would be "property1: sscloud",but it turns out to be "ss",as if it still refers to the scope of the mainCtrl controller, shouldn't it be refer the scope of the d-child directive?

如果我在指令中使用的模板,它指的是正确的范围,并显示sscloud,任何人都可以告诉我为什么?

if I use template in the directive,it does refer to the right scope and shows 'sscloud',anyone can tell me why?

推荐答案


  • 如果指令没有模板属性(或templateUrl),内内容附加到母体范围。其实之前 此提交 ,内含量得到孤立的范围。检查你的例子,以确认它适用于版本的小于1.2

  • 如果指令确实有一个模板属性,则它会覆盖内部内容(除非trancluded)。

  • 只有当你使用transclusion,那么内部内容附加到同级范围(非隔离)。

  • 之所以角度作品这种方式是让可重用的组件是松耦合的,而不是对你的应用程序的任何副作用。

  • 分离无指令范围不会从同一个元素上的分离指令得到分离范围(的 查看重要提交 )。

  • 指令的模板,反正得到隔离范围。

angular.module('project')
.directive('dChild', function() {
    return {
        restrict: 'A',
        transclude: true,        
        scope: {
            property1: '@',
            property2: '='
        },
        link: function(scope, element, attrs, ctrl, linker) {
          linker(scope, function(clone, scope){
            element.append(clone)
          })
        }
    }
})

我强烈建议你看看这些教程:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆