美元的范围.指令中的项未定义

$scope.item in directive is undefined

本文关键字:未定义 指令 范围 美元      更新时间:2023-09-26

我有一个问题与我的指令和控制器。在范围内的变量项是未定义的指令,即使我在html中传递它。这是我的代码:

app.js:

var app = angular.module("app", ["ngRoute"]);
app.config(["$routeProvider", function($routeProvider) {
    $routeProvider
        .when("/", {
            templateUrl: "views/main.html",
            controller: "MainCtrl" 
        });
}]);

controller.js:

app.controller("MainCtrl", function($scope) {
    $scope.item = "x";
});

directive.js:

app.directive("exampleDirective", function() {
    return {
        restrict: "A",
        scope: {
           item: "="
        },
        templateUrl: "views/item.html"
    };
});

index . html:

<div ng-view></div>

main.html:

<div example-directive item="item"></div>

item.html:

<div>{{ item }}</div>

我把代码改成:

app.directive("exampleDirective", function() {
    return {
        restrict: "A",
        scope: true,
        templateUrl: "views/item.html"
    };
});

,现在作用域中有了"x"。但是为什么它不在指令中呢?

虽然它似乎在最新的Angular稳定http://plnkr.co/edit/6oXDIF6P04FXZB335voR?p=preview中工作得很好,但也许你正试图使用指向某个不存在的地方的templateUrl

另一件事,只有在严格需要的时候才使用原语。如果您需要修改item的值,您将无法这样做,因为您正在使用原语。另外,如果你需要"更多信息"进入你的隔离作用域,并且为了避免属性汤(attr-this="that", attr-that="boop", my-otherstuff="anotheritem.member"等),你可以传递处理更多数据的对象的双向绑定。

或者,如果你需要通过多个控制器、指令等来共享状态,那就使用服务,使用依赖注入,这样就不需要把对象/原语传递给你的隔离作用域,你可以保证状态,这是"Angular方式"的最佳实践。

这个方法可以工作:http://jsfiddle.net/HB7LU/2844/,这基本上是一样的,只是没有路由信息。

var myApp = angular.module('myApp',[]);
myApp.directive("exampleDirective", function() {
    return {
        restrict: "A",
        scope: {
           item: "="
        },
        template: "<div>{{ item }}</div>"
    };
});
function MyCtrl($scope) {
    $scope.item = 'Superhero';
}

带视图:

<div ng-controller="MyCtrl">
    <div example-directive item="item"></div>
</div>

这让我相信这可能是一个作用域问题。因此,请尝试将控制器范围变量封装在容器中:

$scope.cont = { item: 'x' };

在视图

<div example-directive item="cont.item"></div>