使用 ng-include 时丢失范围 [英] Losing scope when using ng-include

查看:24
本文介绍了使用 ng-include 时丢失范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个模块路线:

var mainModule = angular.module('lpConnect', []).配置(['$routeProvider',函数($routeProvider){$routeProvider.when('/home', {template:'views/home.html', controller:HomeCtrl}).当('/admin',{模板:'views/admin.html',控制器:AdminCtrl}).否则({重定向到:'/连接'});}]);

主页 HTML:

partial1 HTML:

<input type="text" ng-model="lineText" size="30" placeholder="在此处输入您的信息"></表单>

HomeCtrl:

function HomeCtrl($scope, $location, $window, $http, Common) {...$scope.views = {partial1:"视图/partial1.html"};$scope.addLine = 函数 () {$scope.chat.addLine($scope.lineText);$scope.lines.push({text:$scope.lineText});$scope.lineText = "";};...}

addLine函数中$scope.lineTextundefined,这可以通过添加ng-controller="HomeCtrl"partial1.html,但是它会导致控制器被调用两次.我在这里错过了什么?

解决方案

这是因为 ng-include 创建了一个新的子作用域,所以 $scope.lineText没有改变.我认为 this 指的是当前范围,所以应该设置 this.lineText.

I have this module routes:

var mainModule = angular.module('lpConnect', []).
    config(['$routeProvider', function ($routeProvider) {
    $routeProvider.
        when('/home', {template:'views/home.html', controller:HomeCtrl}).
        when('/admin', {template:'views/admin.html', controller:AdminCtrl}).
        otherwise({redirectTo:'/connect'});
}]);

Home HTML:

<div ng-include src="views.partial1"></div>

partial1 HTML:

<form ng-submit="addLine()">
    <input type="text" ng-model="lineText" size="30" placeholder="Type your message here">
</form>

HomeCtrl:

function HomeCtrl($scope, $location, $window, $http, Common) {
    ...
    $scope.views = {
        partial1:"views/partial1.html"
    };

    $scope.addLine = function () {
        $scope.chat.addLine($scope.lineText);
        $scope.lines.push({text:$scope.lineText});
        $scope.lineText = "";
    };
...
}

In the addLine function $scope.lineText is undefined, this can be resolved by adding ng-controller="HomeCtrl" to partial1.html, however it causes the controller to be called twice. What am I missing here?

解决方案

This is because of ng-include which creates a new child scope, so $scope.lineText isn’t changed. I think that this refers to the current scope, so this.lineText should be set.

这篇关于使用 ng-include 时丢失范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆