2014-09-11 24 views
10

Tôi có plunker sau:AngularJS - Tại sao biến phạm vi cô lập chỉ thị của tôi là không xác định?

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

Khi tôi chạy này, templateUrl là undefined trong phạm vi. Tại sao?

giả định của tôi ở đây là nó đang cố gắng để tìm thấy một biến có tên template.html trong phạm vi phụ huynh, nhưng không thể, vì vậy nó gán nó vào không xác định. Nếu vậy, làm thế nào để vượt qua điều này trong như một chuỗi thay vì một biến phạm vi?

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

Trả lời

11

Chỉ cần thay đổi phạm vi:

scope: { 
     templateUrl: "@" 
    }, 

bạn sẽ nhận được đầu ra 'template.html'.

Điểm mấu chốt là sự khác biệt giữa '=' và '@'. Bạn có thể tham khảo https://docs.angularjs.org/guide/directive.

+0

API Chỉ thị đã được chuyển đến $ biên dịch [https://docs.angularjs.org/api/ng/service/$compile] –

+1

câu trả lời xuất sắc giải thích sự khác biệt trong từng chi tiết.: http://stackoverflow.com/a/14063373/3123195 –

3

tôi đã tìm ra vấn đề của tôi. Tôi cần sử dụng @ thay vì =.

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

Khi nào bạn sẽ sử dụng dấu bằng (=) vào chỉ thị, bạn phải xác định tài sản này theo giấy phép $ phạm vi, khác khôn ngoan nó không hoạt động, Nó sẽ tạo ra lỗi ''. xem tài liệu góc link. cho dù bạn có thể thử templateUrl: "=?" hoặc dưới phạm vi $.

Theo tài liệu góc

<!-- 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> 

Để giải quyết lỗi này, luôn luôn sử dụng biểu thức đường dẫn với tính chất phạm vi đó là hai chiều dữ liệu-bound:

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

giải pháp của bạn là ở đây plnkr

Các vấn đề liên quan