2014-09-11 137 views
10

我有以下plunker:AngularJS - 爲什麼我的指令隔離範圍變量未定義?

http://plnkr.co/edit/7YUpQ1tEjnUaX01txFcK?p=preview

當我運行此,templateUrl的範圍是不確定的。爲什麼?

這裏我的假設是,它試圖在父範圍中找到一個名爲template.html的變量,但不能,因此它將它分配給未定義的變量。如果是這樣,我如何將它作爲字符串而不是範圍變量傳入?

HTML:

<body ng-app="myApp"> 
    <div ng-controller="TestCtrl"> 
     <test-directive ng-model="testModel" 
         template-url="template.html"> 
     </test-directive> 
    </div> 
</body> 

的.js

var app = angular.module("myApp", []); 

app.controller("TestCtrl", function($scope) { 
    $scope.testModel = {} 
}); 

app.directive("testDirective", function() { 
    return { 
     restrict: 'E', 
     scope: { 
      model: "=ngModel", 
      templateUrl: "=" 
     }, 
     template: "<div ng-include='templateUrl'></div>", 
     link: function (scope, element, attrs) { 
      console.log(scope.templateUrl); // <-- Shows as undefined 
     } 
    } 
}); 

回答

11

只需更改範圍:

scope: { 
     templateUrl: "@" 
    }, 

你會得到輸出 'template.html'。

關鍵是'='和'@'的區別。你可以參考https://docs.angularjs.org/guide/directive

+0

指令API已被移至$ compile。[https://docs.angularjs.org/api/ng/service/$compile] – 2016-03-02 13:00:00

+1

解答詳細差異的優秀答案: http://stackoverflow.com/a/14063373/3123195 – 2016-05-03 13:03:01

3

我想通了,我的問題。我需要使用@而不是=。

app.directive("testDirective", function() { 
    return { 
     restrict: 'E', 
     scope: { 
      model: "=ngModel", 
      templateUrl: "@" 
     }, 
     template: "<div ng-include='templateUrl'></div>", 
     link: function (scope, element, attrs) { 
      console.log(scope.templateUrl); // <-- Works perfectly 
     } 
    } 
}); 
3

當你將等號(=)變爲指令時,你必須在$ scope下定義這個屬性,否則它不起作用,它會產生錯誤''。請參閱角度文檔link。是否可以嘗試templateUrl:「=?」或在$範圍下。

根據角文檔

<!-- ERROR because `1+2=localValue` is an invalid statement --> 
<my-directive bind="1+2"> 

<!-- ERROR because `myFn()=localValue` is an invalid statement --> 
<my-directive bind="myFn()"> 

<!-- ERROR because attribute bind wasn't provided --> 
<my-directive> 

要解決此錯誤,總是使用與被作用域屬性路徑表達式雙向數據綁定:

<my-directive bind="some.property"> 
<my-directive bind="some[3]['property']"> 

您的解決方案是在這裏plnkr

相關問題