无法访问$ scope模型

时间:2016-06-01 16:54:08

标签: html angularjs angularjs-directive

在我的主html中,我有一个加载模板的视图。

<div data-ng-view></div>

每次点击链接时都会加载一个html。

app.config(["$routeProvider", function ($routeProvider) {
'use strict';

$routeProvider
    .when("/", {
        templateUrl: "events.html"      
    }); 

}]);

在这个页面(模板)上,我有一个加载另一个html文件的指令

app.directive('ngPost', function () {
'use strict';

return {
    restrict: 'A',
    templateUrl: 'postbox.html'
};


});

然后,我使用<div data-ng-Post></div>

在我的events.html页面上使用此指令

在邮箱中,我有两个输入字段和一个按钮

<input type="text" id="user" data-ng-model="username" /> 
<input type="text" id="mess" data-ng-model="message"/>
<button data-ng-click="Add(eventid-1, username, message)">Post</button>

单击按钮后,我有一些操作,然后我尝试清除输入字段,但我不能。方法在这里:

 $scope.Add = function (index, uname, msg) {

    var a = {user: uname,   message: msg, time: new Date()};

    $scope.data[index].messages.push(a);

    $scope.message = ''; // clearing here
    $scope.username ='';


};

清理没有发生,我不知道为什么。我的具有此Add方法的控制器将<div data-ng-view></div>包装在主html文件中,因此它是最外层的控制器,并且应该可以访问其中的所有$ scope模型。为什么不起作用? 请注意,清算前的操作没有问题

1 个答案:

答案 0 :(得分:2)

您的add方法位于父范围内。父母的范围看不到它的孩子,它反过来工作。消息和用户名属性在指令的子范围中定义。从孩子那里你可以引用父属性,但不能反过来。

如果你将scope:false和transclude:false添加到你的指令中,它将不会创建它自己的作用域而是使用它的父作用域,所以你的指令看起来像这样:

 angular.module('app', []).controller("myController",myController);

    function  myController($scope){
        var ctrl = this;
        ctrl.hello ="Hello"

    };

    angular.module('app').directive("childThing", function() {
        return {
            template: '<div>{{message}}</div><div>{{username}}</div>',
            scope: false,
            transclude: false,
            controller: function($scope) {
                $scope.username="Mike Feltman"
                $scope.message="Hi Mike"
            }
        }
    })

并且您可以访问指令从父级添加到范围的元素,如下所示:

    <div ng-controller="myController as ctrl">
        {{username}} in the parent.
        <div>{{ctrl.hello}}</div>
        <child-thing></child-thing>
    </div>

使用您的模板更新:              父级中的{{username}}。         {{ctrl.hello}}                  

使用Javascript:

function myController($ scope){         var ctrl = this;         ctrl.hello =“你好”

    $scope.add = function() {
        alert($scope.username)
    }

};

angular.module('app').directive("childThing", function() {
    return {
        template: '<input type="text" id="user" data-ng-model="username" /><input type="text" id="mess" data-ng-model="message"/>',
        scope: false,
        transclude: false,
    }
})