AngularJS控制器变量未传递给子指令

时间:2016-02-11 20:15:06

标签: javascript angularjs angularjs-directive angularjs-scope

我有以下代码。我读到指令可以从父作用域继承对象和变量。我有一个带有子指令的控制器,但我似乎无法在我的指令中得到$scope.title

为什么会这样?

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>'
  };
}

1 个答案:

答案 0 :(得分:3)

您尝试访问指令范围的方式,您必须得到控制台错误$scope is not defined,因为$scope不能直接在指令中使用。

您无法使用$scope变量直接访问HTML上的变量。您应该使用angular指令进行绑定,例如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);
    }
  };
}