自定义指令

时间:2016-05-13 09:12:10

标签: javascript angularjs

我正在使用ng-model创建一个指令。所以我可以将模型传递给这些指令。

以下是我的想法:

app.js

app.directive('testDir', function(){
    return {
        templateUrl: 'assets/views/dir.html',
        restrict: 'E',
        required: 'ngModel'

    };
});

dir.html

<div>
    <h1>Test directive</h1>
    <h3>{{name}}</h3>
</div>

的index.html

<div class="container" ng-controller="testCtrl">
  <test-dir ng-model="user"></test-dir>
</div>

控制器

$scope.user = {
        name: 'John Doe'
    };

我可以看到带有<h1>文字的Test directive标记但<h3>中没有任何内容 标签

我知道这是一个非常初学的问题,但是知道我找不到任何解决方案。

谢谢!

2 个答案:

答案 0 :(得分:2)

试试这个,你需要为ng-model

创建一个范围变量
app.directive('testDir', function(){
        return {
            templateUrl: 'assets/views/dir.html',
            restrict: 'E',
            required: 'ngModel',
            scope: {
                ngModel:'='
            }

        };
    });

HTML

<div>
    <h1>Test directive</h1>
    <h3>{{ngModel}}</h3>
</div>

答案 1 :(得分:2)

scope的语法丢失了。请参阅下面的工作示例

&#13;
&#13;
var app = angular.module("sa", []);

app.controller("testCtrl", function($scope) {
  $scope.user = {
    name: 'John Doe'
  };
});

app.directive('testDir', function() {
  return {
    //templateUrl: 'assets/views/dir.html',
    template: '<div>' +
      '<h1>Test directive</h1>' +
      '<h3>{{fooModel.name}}</h3>' +
      '</div>',
    restrict: 'E',
    required: 'ngModel',
    scope: {
        fooModel: '=ngModel'
    }
  };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="sa" class="container" ng-controller="testCtrl">
  <test-dir ng-model="user"></test-dir>
</div>
&#13;
&#13;
&#13;