2016-02-11 148 views
1

我有以下代码。我读过这个指令可以从它们的父范围继承对象和变量。我有一个带有子指令的控制器,但我似乎无法在我的指令中获得我的$scope.titleAngularJS控制器变量未传递给子指令

这是为什么?

https://plnkr.co/edit/h4YlRPa5ZWQkwPZ3isjZ?p=preview

var mod = angular.module('myApp', []); 

mod.controller('myControl', controlFunc).directive('myDirec', direcFunc); 

function controlFunc($scope){ 
    $scope.title = "John Smith"; 
} 
function direcFunc(){ 
    return { 
    restrict: 'E', 
    template: '<h1>' + $scope.title + '</h1>' 
    }; 
} 
+0

你期望在重击者身上看到什么?我看到“约翰史密斯”。 – Matt

回答

3

您试图访问指令范围的方式,你必须得到控制台错误$scope is not defined,为$scope不是指令直接可用。

您无法直接使用$scope变量访问HTML上的变量。您应该使用角度指令进行绑定,如ng-bind/{{}}(插值指令)在这种情况下会有帮助。

您的指令模板应该如下所示。

function direcFunc(){ 
    return { 
    restrict: 'E', 
    scope: false, //by default false, means will not create a new scope 
    //template: '<h1>{{title}}</h1>', //alternative 
    template: '<h1 ng-bind="title"></h1>' 
    }; 
} 

当前你在想什么是不正确的,这里的指令并没有创建任何类型的子范围。基本上默认情况下,指令使用scope: false选项,其中指示指令不使用现有指令创建任何范围。如果您想确认指令范围与控制器的指令范围相同,那么您可以在指令链接函数中放入console.log(scope)

function direcFunc(){ 
    return { 
    restrict: 'E', 
    scope: false, //by default false, means will not create a new scope 
    //template: '<h1>{{title}}</h1>', //alternative 
    template: '<h1 ng-bind="title"></h1>', 
    link: function(scope, element, attrs){ 
     console.log("Below scope will be same as that of controller"); 
     console.log(scope); 
    } 
    }; 
} 
+0

那么,如果我专门使用'ng-bind',指令只会继承控制器内容?无论如何要让指令立即继承控制器的所有内容? – gespinha

+0

@GEspinha让我完成我的答案..我也会涉及这一点.. –

+0

我已经使用'link'函数来'console.log'指令的范围,它的范围和控制器,但为什么我不能使用'$ scope.title'控制器,如果它的范围相同? – gespinha

相关问题