【问题标题】:Binding model in custom directive using this keyword使用此关键字在自定义指令中绑定模型
【发布时间】:2017-07-03 17:17:36
【问题描述】:

Students.html

<div class="row">
    <student info="ui.Ram"></student>
</div>

    

Student.directive 模板

<h1>{{ui.name}}</h1>

路由配置

app.config(urlRouter);
     
       function urlRouter($routeProvider, $locationProvider) {
   
    $routeProvider
       .when('/students', {
           templateUrl: 'app/views/students.html',
           controller: 'prodCtrl',
           controllerAs: 'ui'
       })
       }

  

自定义指令

     app.directive('student', "student");

    function student() {
        var directive = {};
        directive.restrict = 'E';
        directive.templateUrl = "Student.directive.html";
        directive.scope = {
           ui : "=name"
        }
        return directive;
     });

控制器

     app.controller('StudentController', StudentController);
     
     function StudentController($scope) {
        
        $scope.Ram= {};
        $scope.Ram.name = "Mahesh";
        
     };
        

当我这样做时,名称(“Mahesh”)会反映在 UI 中。

我想在控制器中不注入 $scope 的情况下做同样的事情。 像这样。

      function StudentController() {
        var  vm = this;
        vm.Ram= {};
        vm.Ram.name = "Mahesh";
        
       return vm;
     };

但价值并没有体现出来。

【问题讨论】:

    标签: javascript angularjs angular-directive


    【解决方案1】:

    您需要使用controller as 语法来做到这一点:

      <div ng-app = "app" ng-controller = "StudentController as ctrl">
         <student name = "ctrl.Ram"></student>
      </div>
    

    【讨论】:

    • 谢谢!!同时我尝试了同样的方法,但我拥有的其他场景仍然没有渲染
    • 创建一个重现问题的插件
    • 对不起!!我在这里自己更新我的问题,请检查
    猜你喜欢
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多