如何使用范围变量从控制器获取值到指令

时间:2014-07-11 06:20:28

标签: angularjs angular-directive

我在app.js中定义了一个控制器和指令,并在index.html中使用它。

app.js

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
    $scope.name = 'World';
});
app.directive('search', function() {
    return {
        scope: {
            display: '='
        },
        restrict: 'AE',
        replace: true,
        link: function(scope, elm, attrs) {
            alert(display);
        }
    };
});

的index.html

<!DOCTYPE html>
<html ng-app="plunker">
<head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>
        document.write('<base href="' + document.location + '" />');
    </script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js" data-semver="1.2.17"></script>
    <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
    <search display="name"></search>
</body>
</html>

当我在我的指令中发出警告(显示)时,它应该打印“世界”。

1 个答案:

答案 0 :(得分:0)

应为scope.display

    link: function(scope, elm, attrs) {
       alert(scope.display);
    }